【发布时间】:2011-06-01 03:12:12
【问题描述】:
考虑以下类:
public class Code : IEquatable<Code>
{
public string Value { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as Code);
}
public override bool Equals(Code code)
{
if (code == null) return false;
return this.Value == code.Value;
}
public static bool operator ==(Code a, Code b)
{
if (a == null) return b == null;
return a.Equals(b);
}
public static bool operator !=(Code a, Code b)
{
if (a == null) return b!= null;
return !a.Equals(b);
}
// rest of the class here
}
现在尝试使用== 方法:
Code a = new Code();
Code b = new Code();
Console.WriteLine("The same? {0}", a==b);
结果是 StackOverflowException,因为 == 方法在检查 null 时会调用自己。
但是如果我取出空检查:
public static bool operator ==(Code a, Code b)
{
return a.Equals(b);
}
我收到了NullReferenceException!
定义这些方法的正确方法是什么?
【问题讨论】: