作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试想出一种在从 Vector2[] 调用时覆盖 GetHashCode() 的方法。此代码为我知道相等的对象生成非唯一哈希:我将相同的矩形传递给以下类,并生成不同的哈希代码。
public Shape(Rectangle r)
{
edges = new Vector2[4];
edges[0] = new Vector2(0, 0);
edges[1] = new Vector2(r.Width, 0);
edges[2] = new Vector2(r.Width, r.Height);
edges[3] = new Vector2(0, r.Height);
Console.Write(edges.GetHashCode() + "\n");
Position = new Vector2(r.X, r.Y);
}
Vector2 数组只是一堆整数。如何为整数列表创建唯一的散列?
最佳答案
你可以这样使用:
public static int CombineHashCodes(params int[] hashCodes)
{
if (hashCodes == null)
{
throw new ArgumentNullException("hashCodes");
}
if (hashCodes.Length == 0)
{
throw new IndexOutOfRangeException();
}
if (hashCodes.Length == 1)
{
return hashCodes[0];
}
var result = hashCodes[0];
for (var i = 1; i < hashCodes.Length; i++)
{
result = CombineHashCodes(result, hashCodes[i]);
}
return result;
}
private static int CombineHashCodes(int h1, int h2)
{
return (h1 << 5) + h1 ^ h2;
// another implementation
//unchecked
//{
// var hash = 17;
// hash = hash * 23 + h1;
// hash = hash * 23 + h2;
// return hash;
//}
}
关于c# - 如何在 C# 中散列一个 int[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812335/
我是一名优秀的程序员,十分优秀!