在 Microsoft 的 MSDN 库文章中 IEquatable<T>.Equals
方法( http://msdn.microsoft.com/en-us/library/ms131190.aspx )提供了一个示例来演示如何覆盖 Equals 和 Equality 运算符。它看起来像这样:
public class Person : IEquatable<Person>
{
private string uniqueSsn;
private string lName;
public bool Equals(Person other)
{
if (other == null)
return false;
if (this.uniqueSsn == other.SSN)
return true;
else
return false;
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
Person personObj = obj as Person;
if (personObj == null)
return false;
else
return Equals(personObj);
}
public static bool operator == (Person person1, Person person2)
{
if ((object)person1 == null || ((object)person2) == null) // Here !!!
return Object.Equals(person1, person2);
return person1.Equals(person2);
}
...
}
我的注意力被这一行吸引了:if ((object)person1 == null || ((object)person2) == null) return Object.Equals(person1, person2);
据我了解,静态 Object.Equals 会自动检查其参数是否为 null。为什么在调用之前还要再次检查 null 呢?有这样做的指南吗?
我会像这样简单地实现它:
public static bool operator == (Person person1, Person person2)
{
return Object.Equals(person1, person2);
}
或者也许是这样:
public static bool operator == (Person person1, Person person2)
{
if ((object)person1 == null)
return ((object)person2 == null)
return person1.Equals(person2);
}
基于同一文档中的引用:“如果您确实重写 Object.Equals(Object)
,则在调用类上的 static Equals(System.Object, System.Object)
方法时也会调用您的重写实现”
更新:
我在public bool Equals(Person other)
中发现了一个可能的错误,上面写着:other == null
哪里==
重载了!尽管结果是正确的,但存在额外的间接层。我相信应该是(object)other == null
.
最佳答案
您的方法最终将调用虚拟Equals(Object)
方法,因为这就是Object.Equals
的作用。这里给出的方式仅在至少一个值为 null 时使用 Object.Equals
,以便在它们同时为 null 和 false 时返回 true
- 否则path 永远不会回调到您的 Equals
实现。
如果两个值都非空,MSDN 方法将直接对 bool Equals(Person)
进行非虚拟调用 - 这不仅避免了虚拟方法间接,但也是另一种类型检查,当我们已经知道如果引用非空,则它们都是 Person
引用时,这是多余的。
我认为这个例子很不幸,因为它混合使用了字段和属性,请注意 - 我肯定会这样写:
if (this.uniqueSsn == other.SSN)
return true;
else
return false;
正如:
return this.uniqueSsn == other.SSN;
或更明显的是:
return this.uniqueSsn == other.uniqueSsn;
关于c# - MSDN 代码示例 : Why does it check null before calling static Object. 等于吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17571534/