如何获得枚举的属性 [英] How to get attributes of enum

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

问题描述


  

可能重复:结果
  获取枚举值属性


这是我的类:

  [AttributeUsage(AttributeTargets.Field)
公共密封类LabelAttribute:属性
{    公共LabelAttribute(字符串标签)
    {
        NAME =标签;
    }    公共字符串名称{;组; }}

和我想要得到的属性的字段:

 公开枚举ECategory
{
    [标签(安全)]
    安全,
    [标签(LetterDepositBox)]
    LetterDepositBox,
    [标签(SavingsBookBox)]
    SavingsBookBox,
}


解决方案

阅读ECategory.Safe标签的属性值:

  VAR类型= ty​​peof运算(ECategory);
VAR信息= type.GetMember(ECategory.Safe.ToString());
VAR属性=信息[0] .GetCustomAttributes(typeof运算(LabelAttribute),FALSE);
VAR标签=((LabelAttribute)属性[0])名称。

Possible Duplicate:
Getting attributes of Enum’s value

This is my class:

[AttributeUsage(AttributeTargets.Field)]
public sealed class LabelAttribute : Attribute
{

    public LabelAttribute(String labelName)
    {
        Name = labelName;
    }

    public String Name { get; set; }

}

and I want to get the fields of the attributes:

public enum ECategory
{
    [Label("Safe")]
    Safe,
    [Label("LetterDepositBox")]
    LetterDepositBox,
    [Label("SavingsBookBox")]
    SavingsBookBox,
}

解决方案

Read the ECategory.Safe Label attribute value:

var type = typeof(ECategory);
var info = type.GetMember(ECategory.Safe.ToString());
var attributes = info[0].GetCustomAttributes(typeof(LabelAttribute), false);
var label = ((LabelAttribute)attributes[0]).Name;

这篇关于如何获得枚举的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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