Parse string to enum type

后端 未结 8 1164
灰色年华
灰色年华 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<T>
    {
        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.

    0 讨论(0)
  • 2020-11-29 10:02

    This is an old question, but now .NET 4.5 has Enum.TryParse().

    http://msdn.microsoft.com/en-us/library/dd991317.aspx

    0 讨论(0)
提交回复
热议问题