RuntimeHelpers.GetHashCode的作用RuntimeHelpers.GetHashCode(object)方法允许根据对象的身份生成哈希码。MSDN声明:RuntimeHelpers.GetHashCode方法始终以非虚拟方式调用Object.GetHashCode方法,即使对象的类型已覆盖Object.GetHashCode方法。[MethodImpl(MethodImplOptions.InternalCall)][SecuritySafeCritical]publicstaticexternintGetHashCode(objecto);但是,当使用Reflector(.NET4.0)检查Object.GetHashCode()方法时,我们看到以下代码:这使我相信MSDN文档是错误的,因为从RuntimeHelpers.GetHashCode(object)调用Object.GetHashCode会导致堆栈溢出。那么RuntimeHelpers.GetHashCode(object)的实际行为是什么?它是如何工作的?它是如何计算哈希值的?我认为MSDN文档试图描述行为,而不是实现。关键点:RuntimeHelpers返回的默认实现是object.GetHashCode(),它没有被覆盖。这很有用,例如,如果您想要构建引用相等性查找,即使对于重写的Equals和GetHashCode类型也是如此。我在使用RuntimeHelpers.GetHashCode()和Object.ReferenceEquals维护的序列化程序中执行此Object.ReferenceEquals。关键是object.GetHashCode()可以被覆盖——通常用于字符串。这意味着您无法找到object.GetHashCode()的默认实现返回的“身份哈希码”。如果你想实现一个只考虑对象标识的平衡比较器(例如,对于HashSet),这会很有用。例如:publicclassIdentityComparer:IEqualityComparerwhereT:class{publicboolEquals(Tx,Ty){//为清楚起见...returnobject.ReferenceEquals(x,y);}publicintGetHashCode(Tx){//由于在//RuntimeHelpers.GetHashCode中进行了类似的检查,因此可能不需要进行nullity检查,但没有记录returnx==null?0:RuntimeHelpers.GetHashCode(x);然后:stringx="hello";字符串y=newStringBuilder("h").Append("ello").ToString();Console.WriteLine(x==y);//真(重载==)Console.WriteLine(x.GetHashCode()==y.GetHashCode());//True(重写)IdentityComparercomparer=newIdentityComparer();Console.WriteLine(comparer.Equals(x,y));//错误-不是身份//很可能是错误的;不能绝对保证(一如既往,冲突是可能的)Console.WriteLine(comparer.GetHashCode(x)==comparer.GetHashCode(y));编辑:只是为了澄清......那么RuntimeHelpers.GetHashCode(object)的实际行为是什么?它是如何工作的?观察到的行为来自RuntimeHelpers.GetHashCode(object)返回的值与从对Object.GetHashCode()的非虚拟调用返回的值相同(您不能轻易地在C#中编写非虚拟调用。)至于它是如何工作的-这是一个实现细节:)IMO事情发生在哪个区域并不重要(所谓的什么)。重要的是记录在案的行为,这是正确的。哎呀,不同版本的mscorlib可以不同地实现它-从用户的角度来看根本无关紧要。不反编译,你应该看不出来。针对RuntimeHelpers.GetHashCode()记录Object.GetHashCode使其(IMO)更加混乱。奇怪的是,当我通过Reflector查看System.Object.GetHashCode时,我看到publicvirtualintGetHashCode(){returnInternalGetHashCode(this);}和runtimehelper:publicstaticintGetHashCode(objecto){returnobject.InternalGetHashCode(o);也许这是框架差异?我正在查看2.0组件。从您自己的问题看来,RuntimeHelpers.GetHashCode(Object)实际上是未覆盖的Object.GetHashCode()。以上就是C#学习教程的全部内容:RuntimeHelpers.GetHashCode做了什么分享。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权请点击右侧联系管理员删除。如需转载请注明出处:
