根据 this article , 我的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;
}
问题是,虽然它在我添加运算符重新定义之前工作,但现在我得到 StackOverflowException。我错过了什么?
最佳答案
一旦您定义了一个比较Thing
的==
运算符,当您说someThing == null
时就会使用它。 !=
也是如此。
所以如果你说 self == other
,你最终会调用 operator ==(self, other)
。在您的标准中,您有 self != null
,它调用 operator !=(self, null)
...检查是否 self == null
,从而调用 operator ==(self, null)
,然后一圈又一圈,直到用完堆栈空间。
我很确定您可以通过将内容转换为 object
来解决这个问题,以便进行引用比较。或者,你可以说 Object.ReferenceEquals(self, null)
等,它不依赖于 ==
所以你不会得到递归。
关于c# - StackOverflow 在设计比较运算符时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864793/