【问题标题】:How to get attributes of enum [duplicate]如何获取枚举的属性[重复]
【发布时间】:2012-11-09 12:55:49
【问题描述】:

可能重复:
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,
}

【问题讨论】:

    标签: c# attributes field


    【解决方案1】:

    读取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;
    

    【讨论】:

      【解决方案2】:

      你可以创建一个扩展:

      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();
      

      【讨论】:

      • 我认为您在函数中缺少参数名称
      【解决方案3】:
      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];
      

      【讨论】:

        猜你喜欢
        • 2011-05-21
        • 2020-12-31
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        相关资源
        最近更新 更多