Enum from string, int, etc

后端 未结 7 943
伪装坚强ぢ
伪装坚强ぢ 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 08:08

    Another approach (for the string part of your question):

    /// 
    /// Static class for generic parsing of string to enum
    /// 
    /// Type of the enum to be parsed to
    public static class Enum
    {
        /// 
        /// Parses the specified value from string to the given Enum type.
        /// 
        /// The value.
        /// 
        public static T Parse(string value)
        {
            //Null check
            if(value == null) throw new ArgumentNullException("value");
            //Empty string check
            value = value.Trim();
            if(value.Length == 0) throw new ArgumentException("Must specify valid information for parsing in the string", "value");
            //Not enum check
            Type t = typeof(T);
            if(!t.IsEnum) throw new ArgumentException("Type provided must be an Enum", "T");
    
            return (T)Enum.Parse(typeof(T), value);
        }
    }
    

    (Partially inspired by: http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx)

提交回复
热议问题