我有一种枚举类型,其中包含带空格的项目

     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;
        }
      }


当我使用Enum.TryParse(testValue,out stEnum)时,它总是返回第一个元素。

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

最佳答案

您可以从Enum描述中解析Enum,但是您需要从描述中检索Enum值。请检查以下示例,该示例从Enum描述中检索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);
    }


解析示例:

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

07-24 09:38
查看更多