C#中值相等的自定义类的最强大的Equals实现

C#中值相等的自定义类的最强大的Equals实现,第1张

概述假设我有一个Point2类,我想实现以下Equals: public override bool Equals ( object obj )public bool Equals ( Point2 obj ) 这来自Effective C#3书: public override bool Equals ( object obj ){ // STEP 1: Check for null 假设我有一个Point2类,我想实现以下Equals:

public overrIDe bool Equals ( object obj )public bool Equals ( Point2 obj )

这来自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 ) ) );}

这有点矫枉过正吗?

解决方法 支持与继承层次结构的相等性是棘手的.你需要弄清楚你的意思.你真的需要继承吗?如果不是 – 如果Point2直接从System.Object派生,并且你可以使它密封,生活变得容易一些.在那种情况下,我会使用:

public overrIDe bool Equals (object obj){    return Equals(obj as Point2);}public bool Equals (Point2 obj){    // STEP 1: Check for null if nullable (e.g.,a reference type)    // Note use of ReferenceEquals in case you overload ==.    if (object.ReferenceEquals(obj,null))    {        return false;    }    // STEP 2: Check for ReferenceEquals if this is a reference type    // Skip this or not? With only two fIElds to check,it's probably    // not worth it. If the later checks are costly,it Could be.    if (object.ReferenceEquals( this,obj))    {        return true;    }    // STEP 4: Possibly check for equivalent hash codes    // Skipped in this case: would be *less* efficIEnt    // STEP 5: Check base.Equals if base overrIDes Equals()    // Skipped in this case    // STEP 6: Compare IDentifying fIElds for equality.    // In this case I'm using == instead of Equals for brevity    // - assuming X and Y are of a type which overloads ==.    return this.X == obj.X && this.Y == obj.Y;}
总结

以上是内存溢出为你收集整理的C#中值相等的自定义类的最强大的Equals实现全部内容,希望文章能够帮你解决C#中值相等的自定义类的最强大的Equals实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1215313.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存