How to get raw hash code from a class that re-implements GetHashCode?

孤人 提交于 2019-12-10 10:17:46

问题


Short question: How do I get the object.GetHashCode() value for an object that has re-implemented GetHashCode()?

Long story: So I have about a hundred thousand objects, each sharing many (non-compile time) common strings. Common as in if the value is equal, it is the same instance.

Knowing that, I figure I'd rather use a standard object comparison (ReferenceEquals) rather than a full string compare - particularly as these are looked up in dictionaries on a fairly regular basis.

So I declare a class ReferenceEqualityComparer : IEqualityComparer to use with a Dictionary<string, TValue>, figuring it'd be useful to have anyway, and go about trying to implement the two methods.

Equals is easy enough, use object.ReferenceEquals.

But how do I get the equivalent of object.GetHashCode() for the GetHashCode method?

ie how do I get some representation of an object's instance?

I know there are other ways I can go about doing this - create an InternedString class which holds a reference to the string, but does not implement Equals or GetHashCode, or store indexes rather than strings with each object, but I'm now curious - is there actually a way to implement a generic ReferenceEqualityComparer?


回答1:


Have a look at RuntimeHelpers.GetHashCode(object).



来源:https://stackoverflow.com/questions/7414783/how-to-get-raw-hash-code-from-a-class-that-re-implements-gethashcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!