Enum to int best practice

This question already has an answer here:

  • Get int value from enum in C# 24 answers

  • In addition to @dtb

    You can specify the int (or flag) of your enum by supplying it after the equals sign.

    enum MyEnum
    {
        Foo = 0,
        Bar = 100,
        Baz = 9999
    }
    

    Cheers


    If you have an enum such as

    enum MyEnum
    {
        Foo,
        Bar,
        Baz,
    }
    

    and a value of that enum such as

    MyEnum value = MyEnum.Foo;
    

    then the best way to convert the value to an int is

    int result = (int)value;
    

    我会在Enum上以扩展方法的形式向混合中引入第三种替代方法

    public static int ToInt(this Enum e)
    {
        return Convert.ToInt32(e);
    }
    
    enum SomeEnum
    {
        Val1 = 1,
        Val2 = 2,
        Val3 = 3,
    }
    
    int intVal = SomeEnum.ToInt();
    
    链接地址: http://www.djcxy.com/p/91782.html

    上一篇: 如何将字符串转换为枚举值为整数?

    下一篇: 使用int最佳实践