设计比较运算符时的StackOverflow

Kon*_*ten 2 c# equals operator-keyword

根据这篇文章,我附上了我的Equal(Thing)如下.

public override int GetHashCode() { return Id.GetHashCode(); }

public override bool Equals(object input)
{
  Thing comparee = input as Thing;
  return comparee != null && comparee.Id == Id;
}

public static bool operator ==(Thing self, Thing other)
{
  return self != null && other != null && self.Id == other.Id;
}

public static bool operator !=(Thing self, Thing other)
{
  return self == null || other == null || self.Id != other.Id;
}
Run Code Online (Sandbox Code Playgroud)

问题是,在我添加运算符重定义之前它正在工作,现在我得到StackOverflowException.我错过了什么?

cHa*_*Hao 5

一旦定义了一个==比较Things 的运算符,就会在你说的时候使用它someThing == null.同样地!=.

所以,如果你说self == other,你最终会打电话operator ==(self, other).你有自己的标准self != null,它们会调用operator !=(self, null)...来检查你是否self == null,这样调用operator ==(self, null),然后绕过你的堆栈空间.

我非常确定你可以通过投射东西来解决这个问题,以便object进行参考比较.或者,你可以说Object.ReferenceEquals(self, null)等,这不依赖于==你没有得到递归.