Overridding Equals和GetHash [英] Overridding Equals and GetHash
问题描述
我已阅读,当你重写equals上的类/对象则需要重写GetHashCode
I have read that when you override Equals on an class/object you need to override GetHashCode.
public class Person : IEquatable<Person>
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(int personId, string firstName, string lastName)
{
PersonId = personId;
FirstName = firstName;
LastName = lastName;
}
public bool Equals(Person obj)
{
Person p = obj as Person;
if (ReferenceEquals(null, p))
return false;
if (ReferenceEquals(this, p))
return true;
return Equals(p.FirstName, FirstName) &&
Equals(p.LastName, LastName);
}
}
现在给出的以下内容:
public static Dictionary<Person, Person> ObjDic= new Dictionary<Person, Person>();
public static Dictionary<int, Person> PKDic = new Dictionary<int, Person>();
不会overridding的GetHashCode的影响两者的字典的上面?是怎么产生的GetHashCode什么,我基本上是问?如果我仍然期待在PKDic对象将我能够找到它只是基于PK的。如果我想重写的GetHashCode一个人如何会去这样做呢?
Will not overridding the GetHashCode affect both of the Dictionary's above? What I am basically asking is how is GetHashCode generated? IF I still look for an object in PKDic will I be able to find it just based of the PK. If I wanted to override the GetHashCode how would one go about doing that?
推荐答案
您应该的总是 。覆盖的GetHashCode
A 词典< INT,人>
将没有的GetHashCode
,但只要你调用LINQ方法,如鲜明
或 GROUPBY
,它就会停止工作。
A Dictionary<int, Person>
will function without GetHashCode
, but as soon as you call LINQ methods like Distinct
or GroupBy
, it will stop working.
请注意,顺便说一句,你还没有真正覆盖等于
无论是。
中的 IEquatable.Equals
方法是不一样的虚拟BOOL等于(obj对象)
继承自对象
。虽然默认的IEqualityComparer< T>
将使用 IEquatable< T>如果类实现它
接口,你还是应该覆盖等于
,因为其他代码可能不会。
Note, by the way, that you haven't actually overridden Equals
either.
The IEquatable.Equals
method is not the same as the virtual bool Equals(object obj)
inherited from Object
. Although the default IEqualityComparer<T>
will use the IEquatable<T>
interface if the class implements it, you should still override Equals
, because other code might not.
在你的情况,你应该重写等于
和的GetHashCode
是这样的:
In your case, you should override Equals
and GetHashCode
like this:
public override bool Equals(object obj) { return Equals(obj as Person); }
public override int GetHashCode() {
return FirstName.GetHashCode() ^ LastName.GetHashCode();
}
这篇关于Overridding Equals和GetHash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!