说明

在一个数组的列表中,想要去重复,可能要经过相互比较,这种效率就会变的比较差,但要对数组进行 Hash,还是在一套公认的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 namespace MyTestDemo
{
class MathUtil
{
/// <summary>
/// 获取数组内容的哈希,因为数组的默认哈希值,即使内容相同,数组的默认哈希码也是唯一的
/// </summary>
/// <remarks>
/// See Jon Skeet (C# MVP) response in the StackOverflow thread
/// http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode
/// </remarks>
/// <param name="array">要取Hash值的数组.</param>
/// <returns>当前数组的Hash值</returns>
public static int GetHashCode<T>(T[] array)
{
// if non-null array then go into unchecked block to avoid overflow
if (array != null)
{
unchecked
{
int hash = 17;

// get hash code for all items in array
foreach (var item in array)
{
hash = hash * 23 + ((item != null) ? item.GetHashCode() : 0);
}

return hash;
}
}

// if null, hash code is zero
return 0;
}
}
}

引用

由此可以引出如何获取 object 的 hash 的疑问,参考
http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode