RuntimeHelpers.GetHashCode做了什么
RuntimeHelpers.GetHashCode(object)
方法允许基于对象的标识生成哈希码。 MSDN 声明 :
RuntimeHelpers.GetHashCode方法总是非虚拟地调用Object.GetHashCode方法,即使对象的类型已重写Object.GetHashCode方法。
[MethodImpl(MethodImplOptions.InternalCall)] [SecuritySafeCritical] public static extern int GetHashCode(object o);
但是,在使用Reflector(.NET 4.0)检查Object.GetHashCode()
方法时,我们将看到以下代码:
public virtual int GetHashCode() { return RuntimeHelpers.GetHashCode(this); }
这让我相信MSDN文档是错误的,因为从RuntimeHelpers.GetHashCode(object)
调用Object.GetHashCode
会导致堆栈溢出。
那么RuntimeHelpers.GetHashCode(object)
的实际行为是什么?它是如何工作的? 它是如何计算哈希值的?
我认为MSDN文档试图描述行为 ,而不是实现。 关键点: RuntimeHelpers
返回的默认实现是object.GetHashCode()
没有被覆盖。
例如,如果要构建引用相等性查找,即使对于已重写的Equals
和GetHashCode
类型,这也非常有用。 我使用RuntimeHelpers.GetHashCode()
和Object.ReferenceEquals
在我维护的序列化程序中执行此Object.ReferenceEquals
。
关键是object.GetHashCode()
可以被覆盖 – 并且通常是例如string
。 这意味着你无法找到object.GetHashCode()
返回的默认实现的“身份哈希码”。
如果要实现仅考虑对象标识的均衡比较器(例如,对于HashSet
),这可能很有用。
例如:
public class IdentityComparer : IEqualityComparer where T : class { public bool Equals(T x, T y) { // Just for clarity... return object.ReferenceEquals(x, y); } public int GetHashCode(T x) { // The nullity check may be unnecessary due to a similar check in // RuntimeHelpers.GetHashCode, but it's not documented return x == null ? 0 : RuntimeHelpers.GetHashCode(x); } }
然后:
string x = "hello"; string y = new StringBuilder("h").Append("ello").ToString(); Console.WriteLine(x == y); // True (overloaded ==) Console.WriteLine(x.GetHashCode() == y.GetHashCode()); // True (overridden) IdentityComparer comparer = new IdentityComparer (); Console.WriteLine(comparer.Equals(x, y)); // False - not identity // Very probably false; not absolutely guaranteed (as ever, collisions // are possible) Console.WriteLine(comparer.GetHashCode(x) == comparer.GetHashCode(y));
编辑:只是澄清一下……
那么RuntimeHelpers.GetHashCode(对象)的实际行为是什么?它是如何工作的?
观察到的行为是从RuntimeHelpers.GetHashCode(object)
返回的值与从Object.GetHashCode()
的非虚拟调用返回的值相同。 (您无法轻松地在C#中编写非虚拟调用。)
至于它是如何工作的 – 这是一个实现细节:) IMO在哪些方面发生事情(什么叫什么)并不重要。 重要的是记录的行为,这是正确的。 哎呀,不同版本的mscorlib可以以不同的方式实现它 – 从用户的角度来看根本不重要。 没有反编译,你不应该分辨出来。
根据RuntimeHelpers.GetHashCode()
对Object.GetHashCode
进行记录会使(IMO)更加困惑。
奇怪的是,当我通过Reflector查看System.Object.GetHashCode时,我看到了
public virtual int GetHashCode() { return InternalGetHashCode(this); }
并为runtimehelper:
public static int GetHashCode(object o) { return object.InternalGetHashCode(o); }
也许这是一个框架差异? 我正在看2.0组件。
从你自己的问题看,它看起来像RuntimeHelpers.GetHashCode(Object)
实际上是非重写的Object.GetHashCode()
。
上述就是C#学习教程:RuntimeHelpers.GetHashCode做了什么分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1029736.html