C# 如何通过描述获取枚举值

C# 如何通过描述获取枚举值,c#,enums,C#,Enums,在这里,我必须通过描述获得数据 例子: “新罕布什尔州”前我需要29个 动态不使用索引位置这是一种可以: public enum States { [Description("New Hampshire")] NewHampshire = 29, [Description("New York")] NewYork = 32, } 这里是一个可以用于任何属性的通用方法 States s; var type = typeof(Stat

在这里,我必须通过描述获得数据 例子: “新罕布什尔州”前我需要29个
动态不使用索引位置这是一种可以:

public enum States
{
        [Description("New Hampshire")]
        NewHampshire = 29,
        [Description("New York")]
        NewYork = 32,
}

这里是一个可以用于任何属性的通用方法

States s;
var type = typeof(States);
foreach (var field in type.GetFields())
{
    var attribute = Attribute.GetCustomAttribute(field,
        typeof(DescriptionAttribute)) as DescriptionAttribute;
    if (attribute != null)
    {
        if (attribute.Description == "description")
        {
            s = (States)field.GetValue(null);
            break;
        }
    }
    else
    {
        if (field.Name == "description")
        {
            s = (Rule)field.GetValue(null);
            break;
        }
    }
} 
公共静态类扩展
{
公共静态TatAttribute GetAttribute(此枚举枚举值)
其中:属性
{
返回enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute();
}
}

这将帮助您实现所要尝试的…

您可以将字符串传递给GetDataByDescription方法。我使用了Aydin的answer和GetAttribute方法

public static class Extensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) 
            where TAttribute : Attribute
    {
        return enumValue.GetType()
                        .GetMember(enumValue.ToString())
                        .First()
                        .GetCustomAttribute<TAttribute>();
    }
}
内部类程序
{
私有静态void Main(字符串[]args)
{
Console.WriteLine(GetDataByDescription(“新罕布什尔州”);
}
私有静态int GetDataByDescription(字符串s)
{
foreach(Enum.GetValues中的状态(typeof(States)))
{
if(GetAttribute(state).Description==s)
{
返回(int)状态;
}
}
抛出新的ArgumentException(“无此类状态”);
}
私有静态TatAttribute GetAttribute(枚举枚举值)
其中:属性
{
返回enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute();
}
}

您尝试了什么?对不起,我没有尝试
internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(GetDataByDescription("New Hampshire"));
    }

    private static int GetDataByDescription(string s)
    {
        foreach (States state in Enum.GetValues(typeof (States)))
        {
            if (GetAttribute<DescriptionAttribute>(state).Description == s)
            {
                return (int) state;
            }
        }

        throw new ArgumentException("no such state");
    }

    private static TAttribute GetAttribute<TAttribute>(Enum enumValue)
        where TAttribute : Attribute
    {
        return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute<TAttribute>();
    }
}