C#相等运算符覆盖(==和!=)

Mik*_*sen 6 .net c# operator-overloading

可能重复:
如何在没有无限递归的情况下检查'=='运算符重载中的空值?

我有一个看起来像这样的对象:

public class Tags
{
   int mask;

   public static bool operator !=(Tags x, Tags y)
   {
      return !(x == y);
   }

   public static bool operator ==(Tags x, Tags y)
   {
      return x.mask == y.mask;
   }
}
Run Code Online (Sandbox Code Playgroud)

这适用于将实例相互比较,但我也希望能够处理如下表达式:

if(tags1 == null)
Run Code Online (Sandbox Code Playgroud)

这样做会导致以下行出现异常:

return x.mask == y.mask;
Run Code Online (Sandbox Code Playgroud)

既然ynull.

我已经尝试将此功能更改为:

public static bool operator ==(Tags x, Tags y)
{
   if (x == null && y == null) return true;
   if (x == null || y == null) return false;

   return x.mask == y.mask;
}
Run Code Online (Sandbox Code Playgroud)

但是,这会创建堆栈溢出,因为实现使用自己的重写比较运算符.

==操作员处理比较的诀窍是什么null?谢谢!

Kir*_*huk 8

根据指南:

public static bool operator ==(Tags a, Tags b)
{
    // If both are null, or both are same instance, return true.
    if (System.Object.ReferenceEquals(a, b))
    {
        return true;
    }

    // If one is null, but not both, return false.
    if (((object)a == null) || ((object)b == null))
    {
        return false;
    }

    // Return true if the fields match:
    return a.mask == b.mask;
}
Run Code Online (Sandbox Code Playgroud)

  • +1用于挖掘官方指南. (3认同)

Mic*_*Liu 6

而不是x == null,你可以使用(object)x == nullObject.ReferenceEquals(x, null):

public static bool operator ==(Tags x, Tags y)
{
    if ((object)x == null && (object)y == null) return true;
    if ((object)x == null || (object)y == null) return false;

    return x.mask == y.mask;
}
Run Code Online (Sandbox Code Playgroud)

但你也应该实现EqualsGetHashCode:

public override bool Equals(object obj)
{
    return this.Equals(obj as Tags);
}

public bool Equals(Tags tags)
{
    return (object)tags != null && this.mask == tags.mask;
}

public override int GetHashCode()
{
    return this.mask.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

现在operator ==可以简单地写:

public static bool operator ==(Tags x, Tags y)
{
    return (object)x != null ? x.Equals(y) : (object)y == null;
}
Run Code Online (Sandbox Code Playgroud)