[英]Does default == operator implentation calls ReferenceEquals internally in C#?
I know that ==
operator implentation only do reference check by default, and it doesn't call Object.Equals
virtual method.我知道
==
运算符实现默认只做引用检查,它不调用Object.Equals
虚拟方法。 Since Object
class also have a ReferenceEquals
method that does reference check, so does ==
operator default implentation calls Object.ReferenceEquals
method internally?由于
Object
class 也有一个ReferenceEquals
方法进行引用检查,所以==
运算符默认实现在内部调用Object.ReferenceEquals
方法
The default implementation of ==
for a class (not a struct) that has no ==
operator overload defined, is to do a straight reference comparison with a ceq
instruction.对于没有定义
==
运算符重载的 class(不是结构), ==
的默认实现是使用ceq
指令进行直接引用比较。 It does not call ReferenceEquals
(which cannot be overridden as it is static
).它不调用
ReferenceEquals
(不能被覆盖,因为它是static
)。
The code for ReferenceEquals
is quite simple: ReferenceEquals
的代码非常简单:
public static bool ReferenceEquals (Object objA, Object objB) {
return objA == objB;
}
So it's exactly the same thing.所以这完全一样。
==
checks for equality ==
检查是否相等ReferenceEquals
checks for identity ReferenceEquals
检查身份==
and Equals
on a reference type defaults to a reference check, howevercan be overridden by its actual type, ReferenceEquals
cannot==
和Equals
默认为引用检查,但是可以被其实际类型覆盖, ReferenceEquals
不能Going further via the CLI ECMA specs通过 CLI ECMA 规范更进一步
Identity身份
Equality平等
Identity is implemented via the ReferenceEquals
.身份是通过
ReferenceEquals
实现的。 Equality is implemented via the Equals
method.相等是通过
Equals
方法实现的。
Some examples一些例子
Cat
and Dog
if not in a hierarchical relationship can never be identical.Cat
和Dog
永远不可能相同。Cat
and Dog
are separate instances, they can't be identical.Cat
和Dog
是单独的实例,则它们不能相同。Cat
to Mammal
, preserves the identity and are identicalCat
转换为Mammal
,保留身份并且相同(byte)4
and (int)4
are not identical however they are equivalent (byte)4
和(int)4
不相同,但它们是等价的(byte)4
and (byte)4
are identical and therefore equivalent. (byte)4
和(byte)4
是相同的,因此是等价的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.