Get int value from enum in C#

前端 未结 28 2509
臣服心动
臣服心动 2020-11-22 04:58

I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.

public e         


        
28条回答
  •  半阙折子戏
    2020-11-22 05:27

    My favourite hack with int or smaller enums:

    GetHashCode();
    

    For an enum

    public enum Test
    {
        Min = Int32.MinValue,
        One = 1,
        Max = Int32.MaxValue,
    }
    

    This,

    var values = Enum.GetValues(typeof(Test));
    
    foreach (var val in values)
    {
        Console.WriteLine(val.GetHashCode());
        Console.WriteLine(((int)val));
        Console.WriteLine(val);
    }
    

    outputs

    one
    1
    1
    max
    2147483647
    2147483647
    min
    -2147483648
    -2147483648
    

    Disclaimer:

    It doesn't work for enums based on long.

提交回复
热议问题