考虑以下课程:
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
}
Run Code Online (Sandbox Code Playgroud)
现在尝试使用该==方法:
Code a = new Code();
Code b = new Code();
Console.WriteLine("The same? {0}", a==b);
Run Code Online (Sandbox Code Playgroud)
结果是StackOverflowException因为该==方法在检查null时调用自身.
但如果我拿出空检查:
public static bool operator ==(Code a, Code b)
{
return a.Equals(b);
}
Run Code Online (Sandbox Code Playgroud)
我得到了NullReferenceException!
定义这些方法的正确方法是什么?
| 归档时间: |
|
| 查看次数: |
4848 次 |
| 最近记录: |