Enum of long values in C#

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

    The default underlying type of enum is int. An enum can be any integral type except char.

    If you want it to be long, you can do something like this:

    // 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);
        }
    }
    

    The cast is what is important here. And as @dlev says, the purpose of using long in an enum is to support a large number of flags (more than 32 since 2^32 is 4294967296 and a long can hold more than 2^32).

提交回复
热议问题