How to get enum value by string or int

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

    There are numerous ways to do this, but if you want a simple example, this will do. It just needs to be enhanced with necessary defensive coding to check for type safety and invalid parsing, etc.

        /// 
        /// Extension method to return an enum value of type T for the given string.
        /// 
        /// 
        /// 
        /// 
        public static T ToEnum(this string value)
        {
            return (T) Enum.Parse(typeof(T), value, true);
        }
    
        /// 
        /// Extension method to return an enum value of type T for the given int.
        /// 
        /// 
        /// 
        /// 
        public static T ToEnum(this int value)
        {
            var name = Enum.GetName(typeof(T), value);
            return name.ToEnum();
        }
    

提交回复
热议问题