Consider the following class:
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
}
Now try using the ==
method:
Code a = new Code();
Code b = new Code();
Console.WriteLi开发者_开发知识库ne("The same? {0}", a==b);
The result is a StackOverflowException
because the ==
method calls itself when it checks for null.
But if I take out the null check:
public static bool operator ==(Code a, Code b)
{
return a.Equals(b);
}
I get a NullReferenceException
!
What's the correct way to define these methods?
You can also use (object)a == null
use System.Object.ReferenceEquals(a, null)
Starting in C# 7, you can simply use the is
keyword to do a direct reference comparison. See Thorkil's answer to What is the difference between “x is null” and “x == null”?
精彩评论