![](/img/trans.png)
[英]Equals/GetHashCode override warning in derived class with no state
[英]Override Equals and GetHashCode in class with one field
我有一个 class:
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
。
我认为这不足以重载方法(正确地)。
如何识别对象?
一方面,您可以简化两种方法:
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
,然后应用它们自己的逻辑。
就AbstractDictionaryObject
而言,具有相同LangId
的Derived1
的两个实例将是等价的,而Derived2
的两个实例也是如此——但它们彼此不同,因为它们具有不同的类型。
如果您想给他们不同的 hash 代码,您可以将GetHashCode()
更改为:
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + GetType().GetHashCode();
hash = hash * 31 + LangId;
return hash;
}
但是,不同对象的 hash 代码不必不同……它只是有助于提高性能。 如果您知道您将拥有具有相同LangId
的不同类型的实例,您可能想要这样做,但否则我不会打扰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.