Enum of long values in C#

前端 未结 5 1864
忘掉有多难
忘掉有多难 2021-02-18 13:31

Why does this declaration,

public enum ECountry : long
{
    None,
    Canada,
    UnitedStates
}

require a cast for any of its values?

         


        
5条回答
  •  半阙折子戏
    2021-02-18 14:17

    The issue is not that the underlying type is still int. It's long, and you can assign long values to the members. However, you can never just assign an enum value to an integral type without a cast. This should work:

    public enum ECountry : long
    {
        None,
        Canada,
        UnitedStates = (long)int.MaxValue + 1;
    }
    
    // val will be equal to the *long* value int.MaxValue + 1
    long val = (long)ECountry.UnitedStates;
    

提交回复
热议问题