[英]Whats the Difference between Object.Equals(obj, null) and obj == null
Almost every time I want to check object's equality to null
I use the normal equality check operation 几乎每次我想将对象的相等性检查为
null
我都使用正常的相等检查操作
if (obj == null)
Recently I noticed that I'm using the Object.Equals()
more often 最近我注意到我更频繁地使用
Object.Equals()
if (Object.Equals(obj, null))
and while reading about null checking I fount this Is ReferenceEquals(null, obj) the same thing as null == obj? 在阅读有关空检查的同时,我将这个引用的是引用等于(null,obj)与null == obj相同的东西吗?
if (ReferenceEquals(null, obj))
Whats the difference? 有什么不同? and where/when to use each one?
以及何时/何时使用每一个? plus I found that the last two checks look like the same according to their
summary
另外我发现最后两张支票根据他们的
summary
看起来是一样的
Object.Equals(x, y)
will: Object.Equals(x, y)
将:
x
and y
are both null x
和y
都为null,则返回true x
or y
is null x
或y
只有一个为空,则返回false x.Equals(y)
or y.Equals(x)
- it shouldn't matter which. x.Equals(y)
或y.Equals(x)
- 它应该无关紧要。 This means that whatever polymorphic behaviour has been implemented by the execution-time type of the object x
or y
refers to will be invoked. x
或y
引用的执行时类型实现的任何多态行为。 ReferenceEquals
will not call the polymorphic Equals
method. ReferenceEquals
不会调用多态Equals
方法。 It just compares references for equality. 它只是比较了相等的参考。 For example:
例如:
string x = new StringBuilder("hello").ToString();
string y = new StringBuilder("hello").ToString();
Console.WriteLine(Object.Equals(x, y)); // True
Console.WriteLine(Object.ReferenceEquals(x, y)); // False
Console.WriteLine(x == y); // True due to overloading
Now if you're only checking for nullity, then you don't really want the polymorphic behaviour - just reference equality. 现在,如果你只是检查无效,那么你真的不想要多态行为 - 只是引用相等。 So feel free to use
ReferenceEquals
. 所以随意使用
ReferenceEquals
。
You could also use ==
, but that can be overloaded (not overridden) by classes - it is in the case of string, as shown above. 你也可以使用
==
,但是这可以被类重载 (不被覆盖) - 就像字符串一样,如上所示。 The most common case for using ReferenceEquals
in my experience is when you're implementing ==
: 在我的经验中使用
ReferenceEquals
的最常见情况是当你实现 ==
:
public bool operator ==(Foo x1, Foo x2)
{
if (ReferenceEquals(x1, x2))
{
return true;
}
if (ReferenceEquals(x1, null) || ReferenceEquals(x2, null))
{
return false;
}
return x1.Equals(x2);
}
Here you really don't want to call the ==
implementation, because it would recurse forever - you want the very definite reference equality semantics. 在这里,你真的不想要呼叫的
==
实现,因为它会永远递归-你要很明确的引用相等语义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.