你为什么要来覆盖GetHash code和重载相等运算符时,等于?要来、运算符、GetHash、code

2023-09-04 11:06:20 作者:我热情有限你把握时间

如果不重写 GetHash code 等于当重载等于运算符会导致编译器产生的警告。为什么会是一个好主意,改变任何一个执行?看完上GetHash code埃里克利珀的博客文章它看起来可能不会有太多有用的替代GetHash code的基本实现,为什么我鼓励你的编译器来改变它?

Failing to override GetHashCode and Equals when overloading the equality operator causes the compiler to produce warnings. Why would it be a good idea to change the implementation of either? After reading Eric Lippert's blog post on GetHashCode it's seems like there probably aren't many useful alternatives to GetHashCode's base implementation, why does the compiler I encourage you to change it?

推荐答案

让我们假设你正在实现一个类。

Let's suppose you are implementing a class.

如果您是超载 == 则是生产,有一个类型的的值相等的而不是引用的平等。

If you are overloading == then you are producing a type that has value equality as opposed to reference equality.

鉴于此,现在的问题是是多么令人向往它有一个实现在 == ?和答案是不是很理想的。这似乎是混乱的潜在来源。 (事实上​​,我现在的工作,Coverity的公司,生产缺陷的发现工具来检查,看看你是混乱的价值平等的precisely为此引用相等。巧合的是我只是读了规范它当我看到你的问题!)

Given that, now the question is "how desirable is it to have a class that implements reference equality in .Equals() and value equality in ==?" and the answer is "not very desirable". That seems like a potential source of confusion. (And in fact, the company that I now work for, Coverity, produces a defect discovery tool that checks to see if you are confusing value equality with reference equality for precisely this reason. Coincidentally I was just reading the spec for it when I saw your question!)

此外,如果你将拥有一个实现价值和参考平等,通常的方式做到这一点是覆盖等于和离开班级 == ,而不是其他的方式。

Moreover, if you are going to have a class that implements both value and reference equality, the usual way to do it is to override Equals and leave == alone, not the other way around.

因此​​,假定你已经超负荷 == ,强烈建议您也覆盖等于

Therefore, given that you have overloaded ==, it is strongly suggested that you also override Equals.

如果您正在覆盖等于来产生价值相等,那么你的需要的重写 GetHash code 来匹配,因为你知道,如果你读过我的,你链接到文章。

If you are overriding Equals to produce value equality then you are required to override GetHashCode to match, as you know if you've read my article that you linked to.