【问题标题】:How to check for null in the operator== method?如何在 operator== 方法中检查 null?
【发布时间】: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

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

【问题讨论】:

    标签: c# c#-4.0


    【解决方案1】:

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

    【讨论】:

    • 这个解决方案有一个替代方案,目前有更多的赞成票,所以让我注意到(object)a == null 导致代码更快,以至于ReferenceEquals op== 实现花费了两倍以上只要相当于使用(object)a == null。如果您对Equals 也使用相同的代码,这可能会对您使用此类型作为键的每个Distinct()Dictionary&lt;&gt;HashSet&lt;&gt;ToLookup 等产生连锁反应。跨度>
    • 一个 Linqpad 微基准测试,适用于那些有兴趣使用ReferenceEquals 复制性能问题的人:github.com/EamonNerbonne/ValueUtils/blob/master/…。请注意,显然有时 CLR 会内联它,所以如果你幸运的话,这并不重要。
    【解决方案2】:

    【讨论】:

    • 接受的解决方案(object)a == null更快。
    【解决方案3】:

    从 C# 7 开始,您可以简单地使用 is 关键字进行直接引用比较。见Thorkil's answerWhat is the difference between “x is null” and “x == null”?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2020-04-15
      • 2014-03-07
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多