简体   繁体   English

带空格的枚举.TryParse不工作 - C#

[英]Enum with Spaces .TryParse not working - C#

I have one enum type which is having items with spaces 我有一个枚举类型,其中包含带空格的项目

     public enum Enum1
    {
        [Description("Test1 Enum")]
        Test1Enum,
        [Description("Test2 Enum")]
        Test2Enum,
        [Description("Test3Enum")]
        Test3Enum, 
    }

   public void TestMethod(string testValue)
     {
        Enum1 stEnum;
        Enum.TryParse(testValue, out stEnum);
        switch (stEnum)
        {
            case ScriptQcConditonEnum.Test1Enum:
                Console.Log("Hi");
                break;
        }
      }

When i using Enum.TryParse(testValue, out stEnum) ,It always returns first element. 当我使用Enum.TryParse(testValue,out stEnum)时,它总是返回第一个元素。

 // Currently stEnum returns Test1Enum which is wrong
    Enum.TryParse("Test2 Enum", out stEnum) 

You can parse Enum from Enum description but you need to retrieve Enum value from description. 您可以从枚举描述中解析枚举,但您需要从描述中检索枚举值。 Please check below example, that retrieve Enum value from Enum description and parse it as you want. 请检查以下示例,从Enum说明中检索枚举值并根据需要进行解析。

Enum value from Enum description: Enum描述的枚举值:

public T GetValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum) throw new InvalidOperationException();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }
        throw new ArgumentException("Not found.", "description");
        // or return default(T);
    }

Example of parse: 解析示例:

Enum.TryParse(GetValueFromDescription<Enum1>("Test2 Enum").ToString(), out stEnum);

Enum.TryParse trys to parse the string based on the enum value not description. Enum.TryParse根据枚举值而不是描述来解析字符串。 If your requirement is to parse based on description you need to use reflection to get the attribute value. 如果您的要求是根据描述进行解析,则需要使用反射来获取属性值。 How to do this has already been answered in this SO question: Finding an enum value by its Description Attribute 在这个SO问题中已经回答了如何做到这一点: 通过描述属性查找枚举值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM