C#-String.GetHashCode()->不要用作唯一标识符 [英] C# - String.GetHashCode() -> don't use as unique identifier

查看:492
本文介绍了C#-String.GetHashCode()->不要用作唯一标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读Troelsen的书C#和.NET 4.5框架.书中有一节中有一个覆盖的例子

I am currently reading in Troelsen's book C# and the .NET 4.5 framework. There is a section in the book where he has an example of overriding

public virtual int GetHashCode(); // Defined in System.Object

他说(以下引语来自Troelsen的书):

He says (the following quotation is from Troelsen's book):

鉴于String类已经具有使用字符数据的可靠哈希码算法 如果您可以在类中标识出一个对于所有实例都应该唯一的字段数据(例如,社会安全号码),则只需在该点上调用GetHashCode()即可计算哈希值. 现场数据.

Given that the String class already has a solid hash code algorithm that is using the character data of the String to compute a hash value, if you can identify a piece of field data on your class that should be unique for all instances (such as a Social Security number), simply call GetHashCode() on that point of field data.

他基本上是说某个类具有成员(自动只读属性)

Basically what he says is that a certain class has a member (automatic read-only property)

public string SSN {get; }

,该类的每个实例将具有唯一的字符串值. 现在,假设

and every instance of that class is going to have a unique string value. Now, under the assumption that

// s1 and s2 are strings
s1.GetHashCode() != s2.GetHashCode(); // Assumption: If this true then s1 == s2 is true

他的推理将是有效的.但是,当我在字符串. GetHashCode():

his reasoning would be valid. However, when I read on String.GetHashCode():

如果两个字符串对象相等,则GetHashCode方法返回相同的值.但是,每个唯一的字符串值都没有唯一的哈希码值. 不同的字符串可以返回相同的哈希码.

我想你知道我要去哪里.我想是我缺少什么,如果有的话,请指出正确的方向.

I think you see where I am going with this. I guess it's me who's missing something, if so, please point me in the right direction.

谢谢!

推荐答案

您是正确的,即相等的哈希码不能保证相等的值.

You're right that equal hash codes don't guarantee equal values.

您以为那句话意味着其他意思是错误的.

You're wrong in thinking that that quote means otherwise.

此引用特别是在为包含SSN属性的Person类实现哈希码计算的上下文中.相等的SSN值表示相等的Person值.不同的SSN值表示不同的Person值. (注意:现实中不一定是正确的.)

This quote is specifically in the context of implementing a hash code calculation for a Person class containing an SSN property. Equal SSN values mean equal Person values. Different SSN values mean different Person values. (Note: this is not necessarily true in reality.)

现在,您需要为Person进行哈希码计算,以确保两个相等的Person实例具有相同的哈希码,理想情况下,这可能会使两个不相等的Person实例具有不同的哈希码,尽管后者永远无法保证.由于相等性是根据SSN定义的,因此这意味着重新使用SSN的哈希码已经可以实现.

Now, you need a hash code calculation for Person which guarantees that two equal Person instances have the same hash code, and ideally which makes it likely that two unequal Person instances have a different hash code, although the latter can never be guaranteed. Since equality is defined in terms of the SSN, that means re-using the SSN's hash code achieves that already.

这篇关于C#-String.GetHashCode()->不要用作唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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