Using GetHashCode for getting Enum int value

后端 未结 7 1220
北海茫月
北海茫月 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:38

    I see some comments that describe the disadvantages of using GetHashCode() for many reasons.

    There are some cases where (int)INFLOW_SEARCH_ON.ON_LABEL doesn't work.

    A good way to get the int value from Enum is using GeTTypeCode() method. This method works regardlesss of the underlying type. In this case it is int.

    public enum INFLOW_SEARCH_ON
    {
     ON_ENTITY_HANDLE = 0,         
     ON_LABEL = 1,                 
     ON_NODE_HANDLE = 2            
    } // enum INFLOW_SEARCH_ON
    
    INFLOW_SEARCH_ON selectedType = INFLOW_SEARCH_ON.ON_LABEL;
    
    object val = Convert.ChangeType(selectedType, selectedType.GetTypeCode());
    Console.WriteLine(val);
    

    Output in this case is '1'.

    Reference: Get int value from enum

提交回复
热议问题