这可能看起来有点颠倒,但我想要做的是通过其Description属性从枚举中获取枚举值.
所以,如果我有一个枚举声明如下:
enum Testing
{
[Description("David Gouge")]
Dave = 1,
[Description("Peter Gouge")]
Pete = 2,
[Description("Marie Gouge")]
Ree = 3
}
Run Code Online (Sandbox Code Playgroud)
我希望能够通过提供字符串"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)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是那时候我仍然坚持在内心做什么.也不确定这是否是第一个出路.
Tho*_*que 31
使用此处描述的扩展方法:
Testing t = Enum.GetValues(typeof(Testing))
.Cast<Testing>()
.FirstOrDefault(v => v.GetDescription() == descriptionToMatch);
Run Code Online (Sandbox Code Playgroud)
如果找不到匹配的值,它将返回(Testing)0
(您可能希望None
在枚举中为此值定义成员)
归档时间: |
|
查看次数: |
20363 次 |
最近记录: |