如何最好地为自定义类型实现 Equals? [英] How to best implement Equals for custom types?

查看:40
本文介绍了如何最好地为自定义类型实现 Equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说一个 Point2 类,以下等于:

Say for a Point2 class, and the following Equals:

public override bool Equals ( object obj )

public bool Equals ( Point2 obj )

这是在 Effective C# 3 中显示的:

This is the one that is shown in the Effective C# 3:

public override bool Equals ( object obj )
{
    // STEP 1: Check for null
    if ( obj == null )
    {
        return false;
    }

    // STEP 3: equivalent data types
    if ( this.GetType ( ) != obj.GetType ( ) )
    {
        return false;
    }
    return Equals ( ( Point2 ) obj );
}

public bool Equals ( Point2 obj )
{
    // STEP 1: Check for null if nullable (e.g., a reference type)
    if ( obj == null )
    {
        return false;
    }
    // STEP 2: Check for ReferenceEquals if this is a reference type
    if ( ReferenceEquals ( this, obj ) )
    {
        return true;
    }
    // STEP 4: Possibly check for equivalent hash codes
    if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )
    {
        return false;
    }
    // STEP 5: Check base.Equals if base overrides Equals()
    System.Diagnostics.Debug.Assert (
        base.GetType ( ) != typeof ( object ) );

    if ( !base.Equals ( obj ) )
    {
        return false;
    }

    // STEP 6: Compare identifying fields for equality.
    return ( ( this.X.Equals ( obj.X ) ) && ( this.Y.Equals ( obj.Y ) ) );
}

推荐答案

有一整套 MSDN 上的指南 也是如此.你应该好好阅读它们,它既棘手又重要.

There is a whole set of guidelines on MSDN as well. You should read them well, it is both tricky and important.

我认为最有帮助的几点:

A few points I found most helpful:

  • 值类型没有标识,因此在 struct Point 中,您通常会逐个成员进行比较.

  • Value Types don't have Identity, so in a struct Point you will usually do a member by member compare.

引用类型通常有标识,因此 Equals 测试通常在 ReferenceEquals 处停止(默认值,无需覆盖).但也有例外,比如 string 和您的 class Point2,其中对象没有有用的标识,然后您覆盖 Equality 成员以提供您自己的语义.在这种情况下,请按照指南先处理 null 和其他类型的情况.

Reference Types usually do have identity, and therefore the Equals test usually stops at ReferenceEquals (the default, no need to override). But there are exceptions, like string and your class Point2, where an object has no useful identity and then you override the Equality members to provide your own semantics. In that situation, follow the guidelines to get through the null and other-type cases first.

并且有充分的理由让 GethashCode()operator== 保持同步.

And there are good reasons to keep GethashCode() and operator== in sync as well.

这篇关于如何最好地为自定义类型实现 Equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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