用一个字段覆盖类中的Equals和GetHashCode [英] Override Equals and GetHashCode in class with one field

查看:56
本文介绍了用一个字段覆盖类中的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;
        }

我已经派生了类:

public class Derived1:AbstractDictionaryObject
{...}

public class Derived2:AbstractDictionaryObject
{...}

AbstractDictionaryObject 中,只有一个公共字段: LangId .
我认为这不足以(适当地)重载方法.
如何识别物体?

In the AbstractDictionaryObject is only one common field: LangId.
I think this is not enough to overload methods (properly).
How can I identify objects?

推荐答案

一件事,您可以简化两种方法:

For one thing you can simplify both your methods:

 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;
 }

但是那时候应该没问题.如果这两个派生类具有其他字段,则它们应自己覆盖 GetHashCode Equals 本身,首先调用 base.Equals base.GetHashCode,然后应用自己的逻辑.

But at that point it should be fine. If the two derived classes have other fields, they should override GetHashCode and Equals themselves, first calling base.Equals or base.GetHashCode and then applying their own logic.

AbstractDictionaryObject 而言,具有相同 LangId 的两个 Derived1 实例是等效的,因此两个实例也将等效.> Derived2 -但它们会因为类型不同而彼此不同.

Two instances of Derived1 with the same LangId will be equivalent as far as AbstractDictionaryObject is concerned, and so will two instances of Derived2 - but they will be different from each other as they have different types.

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

If you wanted to give them different hash codes you could change GetHashCode() to:

 public override int GetHashCode()
 {
     int hash = 17;
     hash = hash * 31 + GetType().GetHashCode();
     hash = hash * 31 + LangId;
     return hash;
 }

但是,不同对象的哈希码并没有什么不同……它只是有助于提高性能.如果您知道拥有具有相同 LangId 的不同类型的实例,则可能要执行此操作,否则我不会打扰.

However, hash codes for different objects don't have to be different... it just helps in performance. You may want to do this if you know you will have instances of different types with the same LangId, but otherwise I wouldn't bother.

这篇关于用一个字段覆盖类中的Equals和GetHashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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