使用一个字段在类中覆盖Equals和GetHashCode

use*_*173 2 c# overriding equals gethashcode

我有一节课:

public abstract class AbstractDictionaryObject
    {
        public virtual int LangId { get; set; }

        public override bool Equals(object obj)
        {
            if (obj == null || obj.GetType() != GetType())
            {
                return false;
            }

            AbstractDictionaryObject other = (AbstractDictionaryObject)obj;
            if (other.LangId != LangId)
            {
                return false;
            }

            return true;
        }

        public override int GetHashCode()
        {
            int hashCode = 0;               
            hashCode = 19 * hashCode + LangId.GetHashCode();
            return hashCode;
        }
Run Code Online (Sandbox Code Playgroud)

我派出了类:

public class Derived1:AbstractDictionaryObject
{...}

public class Derived2:AbstractDictionaryObject
{...}
Run Code Online (Sandbox Code Playgroud)

在这AbstractDictionaryObject只是一个共同的领域:LangId.
我认为这不足以超载方法(正确).
我如何识别物体?

Jon*_*eet 6

首先,您可以简化两种方法:

 public override bool Equals(object obj)
 {
     if (obj == null || obj.GetType() != GetType())
     {
         return false;
     }

     AbstractDictionaryObject other = (AbstractDictionaryObject)obj;
     return other.LangId == LangId;
 }

 public override int GetHashCode()
 {
     return LangId;
 }
Run Code Online (Sandbox Code Playgroud)

但那时应该没问题.如果两个派生类有其他的领域,就应该重写GetHashCodeEquals自己,先调用base.Equalsbase.GetHashCode再运用自己的逻辑.

就相关而言,Derived1具有相同的两个实例LangId将是等同的AbstractDictionaryObject,并且两个实例Derived2也将是相同的- 但是它们将具有不同的类型而彼此不同.

如果您想为它们提供不同的哈希码,您可以更改GetHashCode()为:

 public override int GetHashCode()
 {
     int hash = 17;
     hash = hash * 31 + GetType().GetHashCode();
     hash = hash * 31 + LangId;
     return hash;
 }
Run Code Online (Sandbox Code Playgroud)

然而,对于不同的对象的散列码不是不同的...它只是有助于性能.你可能想要这样做,如果你知道你会有不同类型的实例LangId,但我不会打扰.