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