简体   繁体   中英

Enum of long values in C#

Why does this declaration,

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

require a cast for any of its values?

long ID = ECountry.Canada;
// Error Cannot implicitly convert type 'ECountry' to 'long'.
// An explicit conversion exists (are you missing a cast?)

And is there a way to get a long value directly from the enum, besides casting?

This would not work either, for example:

public enum ECountry : long
{
    None = 0L,
    Canada = 1L,
    UnitedStates=2L
}

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;

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).

You must cast an enum to get a value from it or it will remain an enum type.

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

AFAIK, you have got to cast.

The MSDN article says:

"However, an explicit cast is needed to convert from enum type to an integral type" (either int or long)

You can check it out:

Enumeration types (C# reference)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM