获取枚举值的属性 [英] Getting attributes of Enum's value
本文介绍了获取枚举值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能获得枚举值的属性,而不是枚举本身?例如,假设我有以下枚举:
I would like to know if it is possible to get attributes of the enum values and not of the enum itself? For example, suppose I have the following enum:
using System.ComponentModel; // for DescriptionAttribute
enum FunkyAttributesEnum
{
[Description("Name With Spaces1")]
NameWithoutSpaces1,
[Description("Name With Spaces2")]
NameWithoutSpaces2
}
我要的是给定的枚举类型,产生枚举字符串值,并将其描述为2元组。
What I want is given the enum type, produce 2-tuples of enum string value and its description.
值很容易:
Array Values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int Value in Values)
Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), Value);
不过,我如何才能说明属性的值,填充Tuple.Desc?我能想到的如何,如果属性属于枚举自己做,但我在一个不知如何从枚举的价值得到它。
But how do I get description attribute's value, to populate Tuple.Desc? I can think of how to do it if the Attribute belongs to the enum itself, but I am at a loss as to how to get it from the value of the enum.
推荐答案
这应该做你所需要的。
var type = typeof(FunkyAttributesEnum);
var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
false);
var description = ((DescriptionAttribute)attributes[0]).Description;
这篇关于获取枚举值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文