How to get enum value by string or int

后端 未结 10 1272
慢半拍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:16

    Could be much simpler if you use TryParse or Parse and ToObject methods.

    public static class EnumHelper
    {
        public static  T GetEnumValue(string str) where T : struct, IConvertible
        {
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new Exception("T must be an Enumeration type.");
            }
            T val;
            return Enum.TryParse(str, true, out val) ? val : default(T);
        }
    
        public static T GetEnumValue(int intValue) where T : struct, IConvertible
        {
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new Exception("T must be an Enumeration type.");
            }
    
            return (T)Enum.ToObject(enumType, intValue);
        }
    }
    

    As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

提交回复
热议问题