如何获取枚举的属性

时间:2012-11-09 12:55:50

标签: c# attributes field

  

可能重复:
  Getting attributes of Enum’s value

这是我的班级:

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

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

    public String Name { get; set; }

}

我希望得到属性的字段:

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

3 个答案:

答案 0 :(得分:2)

阅读ECategory.Safe Label属性值:

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;

答案 1 :(得分:0)

您可以创建扩展程序:

public static class CustomExtensions
  {
    public static string GetLabel(this ECategory value)
    {
      Type type = value.GetType();
      string name = Enum.GetName(type, value);
      if (name != null)
      {
        FieldInfo field = type.GetField(name);
        if (field != null)
        {
          LabelAttribute attr = Attribute.GetCustomAttribute(field, typeof(LabelAttribute )) as LabelAttribute ;
          if (attr != null)
          {
            return attr.Name;
          }
        }
      }
      return null;
    }
  }

然后你可以这样做:

var category = ECategory.Safe;    
var labelValue = category.GetLabel();

答案 2 :(得分:0)

var fieldsMap = typeof(ECategory).GetFields()
    .Where(fi => fi.GetCustomAttributes().Any(a => a is LabelAttribute))
    .Select(fi => new
    {
        Value = (ECategory)fi.GetValue(null),
        Label = fi.GetCustomAttributes(typeof(LabelAttribute), false)
                .Cast<LabelAttribute>()
                .Fist().Name
    })
    .ToDictionary(f => f.Value, f => f.Label);

之后,您可以检索每个值的标签,如下所示:

var label = fieldsMap[ECategory.Safe];