如何在c#中散列int []

我想从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;
    //}
}
链接地址: http://www.djcxy.com/p/66951.html

上一篇: How to hash an int[] in c#

下一篇: SWI Prolog if statements, how do they work? Generating a simple grid