本文介绍了什么RuntimeHelpers.GetHash code执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RuntimeHelpers.GetHash code(对象)方法允许基于对象的身份生成散列codeS。 MSDN 状态的:

  [MethodImpl(MethodImplOptions.InternalCall)
[SecuritySafeCritical]
公共静态外部INT GetHash code(对象o);
 

然而,当检查使用反射(.NET 4.0)的 Object.GetHash code()的方法,我们会看到下面的code:

 公共虚拟INT GetHash code()
{
    返回RuntimeHelpers.GetHash code(本);
}
 

这使我相信,MSDN文档是错误的,因为调用 Object.GetHash code 从在 RuntimeHelpers.GetHash code(对象)将导致堆栈溢出。

那么,什么是 RuntimeHelpers.GetHash code(对象)的实际行为,它是如何工作的?它是如何计算哈希?

解决方案

我觉得MSDN文档试图描述的的行为,而不是实现。关键点: RuntimeTypeHelpers 返回默认执行,你会得到均 object.GetHash code()没有的覆盖。

如果,例如,你想建立这确实是有用的引用相等的查找,即使对于那些已经覆盖等于和类型 GetHash code 。我这样做,我维持,采用了串行 RuntimeTypeHelpers.GetHash code() Object.ReferenceEquals

The RuntimeHelpers.GetHashCode(object) method allows generating hash codes based on the identity of an object. MSDN states:

[MethodImpl(MethodImplOptions.InternalCall)]
[SecuritySafeCritical]
public static extern int GetHashCode(object o);

However, when inspecting the Object.GetHashCode() method using Reflector (.NET 4.0), we'll see the following code:

public virtual int GetHashCode()
{
    return RuntimeHelpers.GetHashCode(this);
}

This makes me believe that the MSDN documentation is wrong, since calling Object.GetHashCode from within the RuntimeHelpers.GetHashCode(object) would cause a stack overflow.

So what is the actual behavior of RuntimeHelpers.GetHashCode(object) and how does it work? How does it calculate the hash?

解决方案

I think the MSDN documentation is trying to describe the behaviour, not the implementation. The key point: RuntimeTypeHelpers returns the default implementation that you would get were object.GetHashCode() not overridden.

This is really useful if, for example, you want to build a reference equality lookup, even for types that have overridden Equals and GetHashCode. I do this in a serializer that I maintain, using RuntimeTypeHelpers.GetHashCode() and Object.ReferenceEquals.

这篇关于什么RuntimeHelpers.GetHash code执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:21