C# how to calculate hashcode from an object reference

前端 未结 3 817
[愿得一人]
[愿得一人] 2021-02-18 23:50

Folks, here\'s a thorny problem for you!

A part of the TickZoom system must collect instances of every type of object into a Dictionary<> type.

It is imperati

相关标签:
3条回答
  • 2021-02-19 00:12

    You are breaking the pattern, this leads to questions that can't be solved. Method Equals should compare the contents of objects, instead of comparing references. That is what object.Equals does, why override with same behavior?

    Now about GetHashCode. Again, hashcode is hash function applied to contents of object. You can't calculate it by reference only. You could use pointer to object and use it as hash, but in .net objects' addresses can be changed by GC.

    0 讨论(0)
  • 2021-02-19 00:18

    RuntimeHelpers.GetHashCode() does exactly what is needed here.

    0 讨论(0)
  • 2021-02-19 00:21

    The hash code doesn't have to be unique. (But uniqueness will improve performance).
    So - one thing you can do is set the hash code by the type name. All object from the same type will have the same hash code.

    0 讨论(0)
提交回复
热议问题