How to get enum value by string or int

后端 未结 10 1270
慢半拍i
慢半拍i 2020-12-07 12:43

How can I get the enum value if I have the enum string or enum int value. eg: If i have an enum as follows:

public enum TestEnum
{
    Value1 = 1,
    Value         


        
10条回答
  •  误落风尘
    2020-12-07 13:29

    I think you forgot the generic type definition:

    public T GetEnumValue(int intValue) where T : struct, IConvertible //  added
    

    and you can improve it to be most convinient like e.g.:

    public static T ToEnum(this string enumValue) : where T : struct, IConvertible
    {
        return (T)Enum.Parse(typeof(T), enumValue);
    }
    

    then you can do:

    TestEnum reqValue = "Value1".ToEnum();
    

提交回复
热议问题