How to TryParse for Enum value?

前端 未结 14 996
终归单人心
终归单人心 2020-11-29 00:22

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return th

14条回答
  •  鱼传尺愫
    2020-11-29 00:34

    Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.

    public static TEnum ToEnum(this string strEnumValue, TEnum defaultValue)
    {
        if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
            return defaultValue;
    
        return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
    }
    

    Worth noting: a TryParse method was added in .NET 4.0.

提交回复
热议问题