我需要覆盖等于吗? [英] do I need to override Equal?

查看:86
本文介绍了我需要覆盖等于吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些有关重写Equal和GetHashcode的内容,但是当仅具有如下所示的简单Equal方法时是否需要它?

I've read some stuff about overriding Equal and GetHashcode but do I need it when just having a simple own Equal method like below?

如果我必须重写它:

那是为什么? -覆盖GetHashCode()时,我应该使用Id.GetHashCode()吗?

Why is that? - Should I use Id.GetHashCode() when overriding GetHashCode()?

public class Foo {
    public Guid Id { get; } = new Guid();

    public bool Equal(Foo other) {
        if (other == null) return false;
        return Id == other.Id;
    }
}

推荐答案

您的代码看起来像您想要实现 Object.Equals() 方法:

Your code looks like you want to implement IEquatable<Foo> for your object. And MSDN advice to oveeride Object.Equals() method:

如果实现IEquatable,则还应该覆盖基数 Object.Equals(Object)和GetHashCode的类实现,以便 它们的行为与IEquatable的行为一致. 方法.如果确实覆盖Object.Equals(Object),则覆盖 静态调用中也调用了实现 类上的Equals(System.Object,System.Object)方法.在 另外,您应该重载op_Equality和op_Inequality 运营商.这样可以确保所有相等性测试均返回一致 结果.

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.

这篇关于我需要覆盖等于吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆