等于/等于和 == 运算符之间的区别? [英] Difference between Equals/equals and == operator?

查看:41
本文介绍了等于/等于和 == 运算符之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a == ba.Equals(b) 有什么区别?

推荐答案

假设 ab 的类型是引用类型:

Assuming the types of a and b are reference types:

  • 在 Java 中,== 将始终比较 identity - 即两个值是否是对同一对象的引用.这也称为引用相等.Java 没有任何用户定义的运算符重载.

  • In Java, == will always compare for identity - i.e. whether the two values are references to the same object. This is also called reference equality. Java doesn't have any user-defined operator overloading.

在 C# 中,这取决于.除非有处理它的重载运算符,否则 == 将表现得像 Java(即比较引用相等性).但是,如果存在与 abcompile-time 类型匹配的重载(例如,如果它们都声明为字符串),则将调用该重载.这可以按照它想要的方式运行,但它通常实现值相等(即 ab 可以指代不同但 equalem> 值,它仍然会返回 true).

In C# it depends. Unless there's an overloaded operator which handles it, == will behave like Java (i.e. comparing for reference equality). However, if there's an overload which matches the compile-time types of a and b (e.g. if they're both declared as strings) then that overload will be called. That can behave how it wants, but it typically implements value equality (i.e. a and b can refer to different but equal values and it would still return true).

在两种语言中,a.Equals(b)a.equals(b) 将调用虚拟的 Equals/Object 声明的equals 方法,除非a 的编译时类型引入了更具体的重载.这可能会或可能不会在 a 引用的对象的执行时类型中被覆盖.在 .NET 和 Java 中,Object 中的实现也会检查身份.请注意,这取决于执行时间类型,而不是重载解析所依赖的编译时间类型.

In both languages, a.Equals(b) or a.equals(b) will call the virtual Equals/equals method declared by Object, unless a more specific overload has been introduced by the compile-time type of a. This may or may not be overridden in the execution-time type of the object that a refers to. In both .NET and Java, the implementation in Object also checks for identity. Note that this depends on the execution-time type rather than the compilation-time type that overload resolution depends on.

当然,如果 anull 那么当你尝试时你会得到一个 NullReferenceException/NullPointerException调用 a.equals(b)a.Equals(b).

Of course, if a is null then you'll get a NullReferenceException/NullPointerException when you try to call a.equals(b) or a.Equals(b).

这篇关于等于/等于和 == 运算符之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆