Parse string to enum type

后端 未结 8 1196
灰色年华
灰色年华 2020-11-29 09:04

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I\'ll read a string from config file. What I n

8条回答
  •  攒了一身酷
    2020-11-29 10:01

    I have just combined the syntax from here, with the exception handling from here, to create this:

    public static class Enum
    {
        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", "TEnum");
    
            return (T)Enum.Parse(typeof(T), value);
        }
    }
    

    You could twiddle it a bit to return null instead of throwing exceptions.

提交回复
热议问题