c# - 通过描述获取枚举值

标签 c# .net enums

Possible Duplicate:
Get Enum from Description attribute

我有一个使用描述属性的枚举。我希望能够根据传入的字符串设置对象 -> 属性值。如果该字符串与枚举值描述之一匹配,则应选择该值。我是否可以在不使用冗长的 for 循环的情况下做到这一点?

public enum Rule
{
     ....
     [Description("New Seed")]
     Rule2 = 2,
     ....
}

我希望的是这样的

var object = new oject{ rule = Rule.Where(r=> r.description == rulestring)}

最佳答案

        Rule f;
        var type = typeof(Rule);
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == "description"){
                    f = (Rule)field.GetValue(null);
                break;}
            }
            else
            {
                if (field.Name == "description"){
                    f = (Rule)field.GetValue(null);
                break;}
            }
        } 

引用:Get Enum from Description attribute

关于c# - 通过描述获取枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10955517/

相关文章:

c# - Angular 2选择带有对象值的选项

.NET Enum基本类型的Char

.net - 如何在代码中更改 Crystal 报表连接属性?

java - Spring 启动;我们可以在 Java 枚举中使用 @Value

java - 检索 Jaxb 转换的 Enum 类中的 @XmlEnumValue 注释属性值

C#,如何隐藏一种形式并显示另一种形式?

c# - 为控制台获取一个 TextWriter

c# - jquery ajax post 到 .aspx 页面加载 - 如何读取发布的变量?

c# - LINQ 中枚举器的奇怪行为

c# - .NET Core - 构建项目指定 ReferencePath