获取枚举值的属性 [英] Getting attributes of Enum's value

查看:172
本文介绍了获取枚举值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以获取枚举值的属性,而不是枚举本身的属性?例如,假设我有以下枚举:

 使用System.ComponentModel; // for DescriptionAttribute 

枚举FunkyAttributesEnum
{
[描述(Name with Spaces1)]
NameWithoutSpaces1,
[描述(Name with Spaces2 )]
NameWithoutSpaces2
}

我想要的是枚举类型,产生2元组的枚举字符串值及其描述。



价值很简单:

 数组值= System.Enum.GetValues(typeof(FunkyAttributesEnum)); 
foreach(值中的值)
Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum),value);但是如何获取描述属性的值,以填充Tuple.Desc?

如果属性属于枚举本身,我可以想到如何做,但是我从枚举的值中得到它是如何得到的。

解决方案

这应该是你需要的。

  var type = typeof(FunkyAttributesEnum); 
var memInfo = type.GetMember(FunkyAttributesEnum.NameWithoutSpaces1.ToString());
var attributes = memInfo [0] .GetCustomAttributes(typeof(DescriptionAttribute),false);
var description =((DescriptionAttribute)attributes [0])。


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
}

What I want is given the enum type, produce 2-tuples of enum string value and its description.

Value was easy:

Array values = System.Enum.GetValues(typeof(FunkyAttributesEnum));
foreach (int value in values)
    Tuple.Value = Enum.GetName(typeof(FunkyAttributesEnum), value);

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.

解决方案

This should do what you need.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆