How to TryParse for Enum value?

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

    This method will convert a type of enum:

      public static TEnum ToEnum<TEnum>(object EnumValue, TEnum defaultValue)
        {
            if (!Enum.IsDefined(typeof(TEnum), EnumValue))
            {
                Type enumType = Enum.GetUnderlyingType(typeof(TEnum));
                if ( EnumValue.GetType() == enumType )
                {
                    string name = Enum.GetName(typeof(HLink.ViewModels.ClaimHeaderViewModel.ClaimStatus), EnumValue);
                    if( name != null)
                        return (TEnum)Enum.Parse(typeof(TEnum), name);
                    return defaultValue;
                }
            }
            return (TEnum)Enum.Parse(typeof(TEnum), EnumValue.ToString());
        } 
    

    It checks the underlying type and get the name against it to parse. If everything fails it will return default value.

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

    Based on .NET 4.5

    Sample code below

    using System;
    
    enum Importance
    {
        None,
        Low,
        Medium,
        Critical
    }
    
    class Program
    {
        static void Main()
        {
        // The input value.
        string value = "Medium";
    
        // An unitialized variable.
        Importance importance;
    
        // Call Enum.TryParse method.
        if (Enum.TryParse(value, out importance))
        {
            // We now have an enum type.
            Console.WriteLine(importance == Importance.Medium);
        }
        }
    }
    

    Reference : http://www.dotnetperls.com/enum-parse

    0 讨论(0)
提交回复
热议问题