为什么C#不托收实现的GetHashCode? [英] Why does C# not implement GetHashCode for Collections?

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

问题描述

我的东西移植从Java到C#。在Java中的哈希码 A 的ArrayList 取决于它的项目。在C#中,我总是从得到相同的哈希码列表 ...

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天全站免登陆