C#:相同的对象必须具有相同的HashCode吗? [英] C#: Same Object have to Same HashCode?

查看:233
本文介绍了C#:相同的对象必须具有相同的HashCode吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个对象,分别为KM

Let's assume I have two objects called K and M

if(K.Equals(M))
{

}

如果是这样,KM 始终具有相同的

If that's true, K and M always has the same HashCode ?

还是取决于编程语言?

推荐答案

GetHashCode()的合同需要它,但是由于任何人都可以自己制定实现,因此永远不能保证.

The contract for GetHashCode() requires it, but since anyone can make their own implementation it is never guaranteed.

许多类(尤其是哈希表)都需要它才能正常运行.

Many classes (especially hashtables) require it in order to behave correctly.

如果要实现一个类,则应始终确保两个相等的对象具有相同的哈希码.

If you are implementing a class, you should always make sure that two equal objects have the same hashcode.

如果要实现实用程序方法/类,则可以假定两个相等的对象具有相同的哈希码(如果不是,则是另一个类,而不是您的类,这是越野车).

If you are implementing an utility method/class, you can assume that two equal objects have the same hashcode (if not, it is the other class, not yours, that is buggy).

如果您要实现一些具有安全隐患的东西,则不能假定.

If you are implementing something with security implications, you cannot assume it.

这篇关于C#:相同的对象必须具有相同的HashCode吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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