<分区>
这可能看起来有点颠倒,但我想做的是通过其 Description 属性从枚举中获取枚举值。
所以,如果我有一个声明如下的枚举:
enum Testing
{
[Description("David Gouge")]
Dave = 1,
[Description("Peter Gouge")]
Pete = 2,
[Description("Marie Gouge")]
Ree = 3
}
我希望能够通过提供字符串“Peter Gouge”来取回 2。
作为起点,我可以遍历枚举字段并获取具有正确属性的字段:
string descriptionToMatch = "Peter Gouge";
FieldInfo[] fields = typeof(Testing).GetFields();
foreach (FieldInfo field in fields)
{
if (field.GetCustomAttributes(typeof(DescriptionAttribute), false).Count() > 0)
{
if (((DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description == descriptionToMatch)
{
}
}
}
但是我对在那个内部 if 中做什么感到困惑。也不确定这是否是首先要走的路。