当我们做GetHash code()的意思?当我们、意思、GetHash、code

2023-09-02 21:10:38 作者:深巷裏的流浪貓

我已经使用词典(TKEY的,TValue)用于多种用途。但是我还没有遇到任何情况下实现GetHash code(),我相信这是因为我的钥匙是主要的类型,如int和字符串。 我很好奇,想知道的情况下(现实世界的例子)时,应该使用一个自定义对象为重点,从而实现方法GetHash code()等于()等。

I have used Dictionary(TKey, TValue) for many purposes. But I haven't encountered any scenario to implement GetHashCode() which I believe is because my keys were of primary types like int and string. I am curious to know the scenarios (real world examples) when one should use a custom object for key and thus implement methods GetHashCode() Equals() etc.

和,不使用自定义对象的关键必要实现这些功能呢?

And, does using a custom object for key necessitate implementing these functions?

推荐答案

您应该重写等于 GetHash code 当默认 的Object.Equals (测试为引用相等)是不够的。出现这种情况,例如,当你的密钥类型是自定义类型,你想两个键被认为是平等的,即使在情况下,当它们不是自定义类型的同一个实例。

You should override Equals and GetHashCode whenever the default Object.Equals (tests for reference equality) will not suffice. This happens, for example, when the type of your key is a custom type and you want two keys to be considered equal even in cases when they are not the same instance of the custom type.

例如,如果你的关键就是这么简单

For example, if your key is as simple as

class Point {
    public int X { get; set; }
    public int Y { get; set; }
}

和你希望两个的两个被认为是相等的,如果他们的 X 是平等的,他们的 s的平等,那么你将需要重写等于 GetHash code

and you want two Points two be considered equal if their Xs are equal and their Ys are equal then you will need to override Equals and GetHashCode.

 
精彩推荐
图片推荐