Enum of long values in C#

前端 未结 5 1757
忘掉有多难
忘掉有多难 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:11

    From MSDN:

    In this example, the base-type option is used to declare an enum whose members are of the type long. Notice that even though the underlying type of the enumeration is long, the enumeration members must still be explicitly converted to type long using a cast.

    // keyword_enum2.cs
    // Using long enumerators
    using System;
    public class EnumTest
    {
        enum Range :long {Max = 2147483648L, Min = 255L};
        static void Main()
        {
            long x = (long)Range.Max;
            long y = (long)Range.Min;
            Console.WriteLine("Max = {0}", x);
            Console.WriteLine("Min = {0}", y);
        }
    }
    

    Output

    Max = 2147483648 Min = 255

提交回复
热议问题