Using GetHashCode for getting Enum int value

后端 未结 7 1232
北海茫月
北海茫月 2020-12-03 07:20

I have an enum

public enum INFLOW_SEARCH_ON
{
  ON_ENTITY_HANDLE = 0,         
  ON_LABEL = 1,                 
  ON_NODE_HANDLE = 2            
} // enum I         


        
7条回答
  •  一个人的身影
    2020-12-03 07:32

    Using GetHashCode() is incorrect. You should cast to int. Using it the way you do is asking for raptors(or Raymond) to come and eat you.

    That GetHashCode() happens to return the integer value of the enum is an implementation detail and may change in future versions of .net.

    GetHashCode() guarantees that if two values are equal their hash codes are equal too. The other way round is not guaranteed.

    My rule of thumb is that if GetHashCode were to return a constant value your program should still work correctly (but potentially be much slower) since a constant GetHashCode trivially fulfills the contract, but has bad distribution properties.

提交回复
热议问题