2

可能重复:
从描述属性中获取枚举

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

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

我希望是这样的

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

1 回答 1

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

ref:从描述属性中获取枚举

于 2012-06-08T20:26:45.607 回答