C# enum contains value

后端 未结 10 659
轮回少年
轮回少年 2020-12-07 23:46

I have an enum

enum myEnum2 { ab, st, top, under, below}

I would like to write a function to test if a given value is included in myEnum

10条回答
  •  粉色の甜心
    2020-12-08 00:43

       public static T ConvertToEnum(this string value)
        {
            if (typeof(T).BaseType != typeof(Enum))
            {
                throw new InvalidCastException("The specified object is not an enum.");
            }
            if (Enum.IsDefined(typeof(T), value.ToUpper()) == false)
            {
                throw new InvalidCastException("The parameter value doesn't exist in the specified enum.");
            }
            return (T)Enum.Parse(typeof(T), value.ToUpper());
        }
    

提交回复
热议问题