按说明获取枚举值

时间:2012-06-08 20:14:55

标签: c# .net enums

  

可能重复:
  Get Enum from Description attribute

我有一个使用descript属性的Enum。我希望能够设置对象 - >基于传入的字符串的属性值。如果字符串与枚举值描述之一匹配,则应选择该值。如果不使用冗长的for循环,我可以这样做吗?

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

我希望的是

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

1 个答案:

答案 0 :(得分: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;}
            }
        } 

参考:Get Enum from Description attribute