我已经阅读了一些关于覆盖 Equal 和 GetHashcode 的内容,但是当我只有一个简单的自己的 Equal 方法时是否需要它,如下所示?
如果我确实必须覆盖它:
这是为什么呢? - 我应该在覆盖 GetHashCode() 时使用 Id.GetHashCode() 吗?
public class Foo {
public Guid Id { get; } = new Guid();
public bool Equal(Foo other) {
if (other == null) return false;
return Id == other.Id;
}
}
最佳答案
您的代码看起来像您想要实现的 IEquatable<Foo>
为你的对象。和 MSDN 建议超越 Object.Equals()
方法:
If you implement IEquatable, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results.
关于c# - 我需要重写 Equal 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766369/