简体   繁体   中英

c# parsing Enums from long

I have an enum inheriting from a long and use it as a flags in my app.

I have just noticed that I cannot parse values greater than int.MaxValue, am I doing something wrong or is this not supported?

eg...

using System;

public class Program
{
    public static void Main()
    {

        foreach (var option in Enum.GetValues(typeof (A))) {
            Console.WriteLine((long)option + " = " + option);
        }

        foreach (var option in Enum.GetNames(typeof(A))) {
            var name = option;
            var val = Enum.Parse(typeof(A),name);
            Console.WriteLine(option + " is " + ((long)val));
        }

    }

    public enum A : long {      
        Red = 1 << 0,
        Blue = 1 << 32,
        Green = 1 << 33
    }
}

Produces :

1 = Blue
1 = Blue
2 = Green
Red is 1
Blue is 1
Green is 2

Any ideas how to get the correct results?

Do this and you shall see why the problem: Console.WriteLine((int)A.Blue); . Now write Blue = 1L << 32 and solve your problem. (1<<32 is not a large number, it is 0 because 1 and 32 are both integers and so too is 1<<32, and that overflows an integer)

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