3

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

这是我的课:

[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,
}
4

3 回答 3

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;
于 2012-11-09T13:05:38.090 回答
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];
于 2012-11-09T13:09:56.757 回答
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();
于 2012-11-09T13:05:52.130 回答