How to get attributes of enum [duplicate]

非 Y 不嫁゛ 提交于 2019-12-13 14:07:58

问题


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

回答1:


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;



回答2:


You can Create an Extension:

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;
    }
  }

Then you can do:

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

Afterwards you can retrieve the label for each value like this:

var label = fieldsMap[ECategory.Safe];


来源:https://stackoverflow.com/questions/13308481/how-to-get-attributes-of-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!