How to TryParse for Enum value?

前端 未结 14 915
终归单人心
终归单人心 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<TEnum>(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.

    0 讨论(0)
  • 2020-11-29 00:35

    There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.

    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
  • 2020-11-29 00:49

    As others have said, you have to implement your own TryParse. Simon Mourier is providing a full implementation which takes care of everything.

    If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2" which is a combination of two enum values. If you just call Enum.IsDefined with this string, it will return false, even though Enum.Parse handles it correctly.

    Update

    As mentioned by Lisa and Christian in the comments, Enum.TryParse is now available for C# in .NET4 and up.

    MSDN Docs

    0 讨论(0)
  • 2020-11-29 00:49
    enum EnumStatus
    {
        NAO_INFORMADO = 0,
        ENCONTRADO = 1,
        BLOQUEADA_PELO_ENTREGADOR = 2,
        DISPOSITIVO_DESABILITADO = 3,
        ERRO_INTERNO = 4,
        AGARDANDO = 5
    }
    

    ...

    if (Enum.TryParse<EnumStatus>(item.status, out status)) {
    
    }
    
    0 讨论(0)
  • 2020-11-29 00:52

    As others already said, if you don't use Try&Catch, you need to use IsDefined or GetNames... Here are some samples...they basically are all the same, the first one handling nullable enums. I prefer the 2nd one as it's an extension on strings, not enums...but you can mix them as you want!

    • www.objectreference.net/post/Enum-TryParse-Extension-Method.aspx
    • flatlinerdoa.spaces.live.com/blog/cns!17124D03A9A052B0!605.entry
    • mironabramson.com/blog/post/2008/03/Another-version-for-the-missing-method-EnumTryParse.aspx
    • lazyloading.blogspot.com/2008/04/enumtryparse-with-net-35-extension.html
    0 讨论(0)
提交回复
热议问题