如何在operator ==方法中检查null?

MCS*_*MCS 24 c# c#-4.0

考虑以下课程:

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!

定义这些方法的正确方法是什么?

Rex*_*x M 33

你也可以使用 (object)a == null


Ben*_*igt 22

使用 System.Object.ReferenceEquals(a, null)

  • 公认的解决方案`(object)a == null`更快。 (2认同)