Enum from string, int, etc

后端 未结 7 1033
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 07:23

Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt(), ToString()

7条回答
  •  盖世英雄少女心
    2021-01-17 07:55

    why do you want FromInt an extenstion method versus just casting it?

    MyEnum fromInt;
    if(Enum.IsDefined(typeof(MyEnum), intvalue))
    {
        fromInt = (MyEnum) intvalue;
    }
    else
    {
        //not valid
    }
    

    alternatively, for strings, you can use Enum.TryParse

    MyEnum fromString;
    if (Enum.TryParse(stringvalue, out fromString))
    {
        //succeeded
    }
    else
    {
        //not valid
    }
    

提交回复
热议问题