Object.GetHashCode() 的默认实现 [英] Default implementation for Object.GetHashCode()
问题描述
GetHashCode()
的默认实现如何工作?它是否足够有效和良好地处理结构、类、数组等?
How does the default implementation for GetHashCode()
work? And does it handle structures, classes, arrays, etc. efficiently and well enough?
我正在尝试决定在哪些情况下我应该自己打包,以及在哪些情况下我可以安全地依赖默认实现来做好.如果可能的话,我不想重新发明轮子.
I am trying to decide in what cases I should pack my own and in what cases I can safely rely on the default implementation to do well. I don't want to reinvent the wheel, if at all possible.
推荐答案
namespace System {
public class Object {
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern int InternalGetHashCode(object obj);
public virtual int GetHashCode() {
return InternalGetHashCode(this);
}
}
}
InternalGetHashCode 映射到 CLR 中的 ObjectNative::GetHashCode 函数,如下所示:
InternalGetHashCode is mapped to an ObjectNative::GetHashCode function in the CLR, which looks like this:
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* obj) {
CONTRACTL
{
THROWS;
DISABLED(GC_NOTRIGGER);
INJECT_FAULT(FCThrow(kOutOfMemoryException););
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
VALIDATEOBJECTREF(obj);
DWORD idx = 0;
if (obj == 0)
return 0;
OBJECTREF objRef(obj);
HELPER_METHOD_FRAME_BEGIN_RET_1(objRef); // Set up a frame
idx = GetHashCodeEx(OBJECTREFToObject(objRef));
HELPER_METHOD_FRAME_END();
return idx;
}
FCIMPLEND
GetHashCodeEx 的完整实现相当大,因此只需链接到C++ 源代码.
The full implementation of GetHashCodeEx is fairly large, so it's easier to just link to the C++ source code.
这篇关于Object.GetHashCode() 的默认实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!