Parse string to enum type

后端 未结 8 1213
灰色年华
灰色年华 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 09:55

    What about something like:

    public static class EnumUtils
    {
        public static Nullable Parse(string input) where T : struct
        {
            //since we cant do a generic type constraint
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException("Generic Type 'T' must be an Enum");
            }
            if (!string.IsNullOrEmpty(input))
            {
                if (Enum.GetNames(typeof(T)).Any(
                      e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
                {
                    return (T)Enum.Parse(typeof(T), input, true);
                }
            }
            return null;
        }
    }
    

    Used as:

    MyEnum? value = EnumUtils.Parse("foo");
    

    (Note: old version used try/catch around Enum.Parse)

提交回复
热议问题