为什么 C# 不为集合实现 GetHashCode? [英] Why does C# not implement GetHashCode for Collections?

查看:26
本文介绍了为什么 C# 不为集合实现 GetHashCode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些东西从 Java 移植到 C#.在 Java 中,ArrayListhashcode 取决于其中的项目.在 C# 中,我总是从 List...

I am porting something from Java to C#. In Java the hashcode of a ArrayList depends on the items in it. In C# I always get the same hashcode from a List...

这是为什么?

对于我的一些对象,哈希码需要不同,因为它们的列表属性中的对象使对象不相等.我希望哈希码对于对象的状态始终是唯一的,并且仅在对象相等时才等于另一个哈希码.我错了吗?

For some of my objects the hashcode needs to be different because the objects in their list property make the objects non-equal. I would expect that a hashcode is always unique for the object's state and only equals another hashcode when the object is equal. Am I wrong?

推荐答案

为了正常工作,哈希码必须是不可变的——对象的哈希码必须永远改变.

In order to work correctly, hashcodes must be immutable – an object's hash code must never change.

如果一个对象的哈希码确实发生了变化,任何包含该对象的字典都将停止工作.

If an object's hashcode does change, any dictionaries containing the object will stop working.

由于集合不是一成不变的,因此它们无法实现 GetHashCode.
相反,它们继承了默认的 GetHashCode,它为对象的每个实例返回一个(希望如此)唯一的值.(通常基于内存地址)

Since collections are not immutable, they cannot implement GetHashCode.
Instead, they inherit the default GetHashCode, which returns a (hopefully) unique value for each instance of an object. (Typically based on a memory address)

这篇关于为什么 C# 不为集合实现 GetHashCode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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