平等双方之间的差值/ equals和==操作符? [英] Difference between Equals/equals and == operator?
问题描述
什么是 A == b
和 a.Equals之间的差值(B)
?
推荐答案
假设类型的 A
和 B
是引用类型:
Assuming the types of a
and b
are reference types:
-
在Java中,==总是比较对的标识的 - 即两个值是否是同一个对象的引用。这也被称为的引用相等的。 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的(即比较参考平等)。但是,如果有相匹配的过载的编译时间的类型 A
和 B
(例如,如果他们都声明为字符串),那么超载将被调用。这可以表现怎么想,但通常实现的值相等的(即 A
和 B
可以参考,但不同的等于的价值观,它仍然会返回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)
将调用虚拟等于
/ 等于通过
,除非更具体超载已被的编译时类型介绍声明
Method对象 A
。这可能会或可能不会在对象的执行时间类型覆盖的
引用。在这两个.NET和Java中,对象执行
还检查身份。请注意,这依赖于的执行时间型的而不是编译时类型的是重载依赖。
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.
当然,如果 A
是空
,那么你会得到一个的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)
.
这篇关于平等双方之间的差值/ equals和==操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!