.NET等效于java.util.Arrays.hashCode()函数的内部类型数组?

时间:2021-02-23 16:11:42

Is there a.NET utility class equivalent to java.util.Arrays.hashCode() for arrays of intrinsic types such as int[], short[], float[], etc.?

是否有一个.NET实用程序类,相当于java.util.Arrays.hashCode(),用于内部类型的数组,如int [],short [],float []等。

Obviously I could write my own utility class but was trying to find one already available in the .NET framework.

显然,我可以编写自己的实用程序类,但试图找到.NET框架中已有的实用程序类。

3 个解决方案

#1


In .NET 4.0 arrays will support this via the IStructuralEquatable interface, but until that point you'll have to do it yourself I'm afraid.

在.NET 4.0中,数组将通过IStructuralEquatable接口支持这一点,但在此之前,你必须自己做,我担心。

#2


I'm pretty sure there's nothing in the framework itself that does this. There may well be some third-party implementations, but there's nothing built-in (and public).

我很确定框架本身没有任何东西可以做到这一点。可能有一些第三方实现,但没有内置(和公共)。

#3


I'm not aware of such a thing being built-into .Net up to version 3.5, although .Net 4 is very likely to support it natively via the IStructuralEquatable interface which Array will implement (thanks to Greg Beech for pointing that out).

我不知道有这样的东西被内置到.Net版本3.5,尽管.Net 4很可能通过Array将实现的IStructuralEquatable接口本地支持它(感谢Greg Beech指出这一点)。

Here's a simple implementation using an extension method on IEnumerable.

这是在IEnumerable上使用扩展方法的简单实现。

int HashContents<T>(this IEnumerable<T> enumerable)
{
    int hash = 0x218A9B2C;
    foreach (var item in enumerable)
    {
        int thisHash = item.GetHashCode();
        //mix up the bits.
        hash = thisHash ^ ((hash << 5) + hash);
    }
    return hash;
}

This will give different hashcodes for {0,0} and {0,0,0}.

这将为{0,0}和{0,0,0}提供不同的哈希码。

#1


In .NET 4.0 arrays will support this via the IStructuralEquatable interface, but until that point you'll have to do it yourself I'm afraid.

在.NET 4.0中,数组将通过IStructuralEquatable接口支持这一点,但在此之前,你必须自己做,我担心。

#2


I'm pretty sure there's nothing in the framework itself that does this. There may well be some third-party implementations, but there's nothing built-in (and public).

我很确定框架本身没有任何东西可以做到这一点。可能有一些第三方实现,但没有内置(和公共)。

#3


I'm not aware of such a thing being built-into .Net up to version 3.5, although .Net 4 is very likely to support it natively via the IStructuralEquatable interface which Array will implement (thanks to Greg Beech for pointing that out).

我不知道有这样的东西被内置到.Net版本3.5,尽管.Net 4很可能通过Array将实现的IStructuralEquatable接口本地支持它(感谢Greg Beech指出这一点)。

Here's a simple implementation using an extension method on IEnumerable.

这是在IEnumerable上使用扩展方法的简单实现。

int HashContents<T>(this IEnumerable<T> enumerable)
{
    int hash = 0x218A9B2C;
    foreach (var item in enumerable)
    {
        int thisHash = item.GetHashCode();
        //mix up the bits.
        hash = thisHash ^ ((hash << 5) + hash);
    }
    return hash;
}

This will give different hashcodes for {0,0} and {0,0,0}.

这将为{0,0}和{0,0,0}提供不同的哈希码。