c# - 我需要重写 Equal 吗?

标签 c# overriding

我已经阅读了一些关于覆盖 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/

相关文章:

c# - 当我在 WCF 中使用类/属性时,我应该将它们装饰为 DataContract/DataMember 吗?

java - 从内联覆盖方法访问实例

java - 我有一个带有@Override 的方法,如何查看声明接口(interface)?

c++ - 虚拟纯函数

android - 为什么我的 @Override of toString() 方法从未在 Android 上被调用?

c# - Asp.Net:动态切换 UserControl - 如何?

c# - 是否有任何已知的方法来更改命名空间但支持 API 中的旧方法

c# - DbContext -> DbSet -> Where 子句丢失( Entity Framework 6)

c# - 正则表达式模式与输入字符串不匹配

css - Bootstrap 没有覆盖我自己的 css