gpt4 book ai didi

C# - String.GetHashCode() -> 不要用作唯一标识符

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:59 25 4
gpt4 key购买 nike

我目前正在阅读 Troelsen 的《C# 和 .NET 4.5 框架》一书。书中有一节他有一个重写的例子

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

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

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.

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

public string SSN {get; }

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

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

他的推理是有效的。但是,当我阅读 String.GetHashCode() 时:

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.

我想你明白我要用这个做什么。我想是我遗漏了什么,如果是这样,请指出正确的方向。

谢谢!

最佳答案

GetHashCode的目的|不是为对象生成唯一标识符,而是实现基于hash tables的数据结构,例如 Dictionary<K, V> HashSet<T> .

需要哈希函数来确保如果 x == y , 然后 x.GetHashCode() == y.GetHashCode() ,但反之则为真:两个不同的对象可以具有相同的哈希码。这种情况称为哈希冲突

哈希表结构在发生碰撞时仍有效,但它们运行速度较慢,因为您的程序必须花费时间来消除哪个您正在搜索的碰撞对象的歧义.因此,好的 散列函数会尽量减少冲突。 (请注意,如果一个类有超过 232 个可能值,则完全避免冲突在数学上是不可能的,因为 pigeonhole principle。)

那你怎么写好GetHashCode你类(class)的实现?做一些复杂的数学运算,将类(class)的每个字段转换为 int , 然后对其进行分析以确定其中系数的最佳值?

根据 Troelsen 的说法,不。就拿你的“最独特”string现场并调用GetHashCode()在那上面。编写 System.String.GetHashCode 的开发人员知道他们在做什么,所以只要使用它,您就会自动利用他们的“可靠的哈希码算法”。

关于C# - String.GetHashCode() -> 不要用作唯一标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com