How to TryParse for Enum value?

前端 未结 14 998
终归单人心
终归单人心 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:38

    There is not a TryParse because the Enum's type is not known until runtime. A TryParse that follows the same methodology as say the Date.TryParse method would throw an implicit conversion error on the ByRef parameter.

    I suggest doing something like this:

    //1 line call to get value
    MyEnums enumValue = (Sections)EnumValue(typeof(Sections), myEnumTextValue, MyEnums.SomeEnumDefault);
    
    //Put this somewhere where you can reuse
    public static object EnumValue(System.Type enumType, string value, object NotDefinedReplacement)
    {
        if (Enum.IsDefined(enumType, value)) {
            return Enum.Parse(enumType, value);
        } else {
            return Enum.Parse(enumType, NotDefinedReplacement);
        }
    }
    

提交回复
热议问题