How to get attributes of enum
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Getting attributes of Enum’s value
这是我的课:
1 2 3 4 5 6 7 8 9 10 11 12 | [AttributeUsage(AttributeTargets.Field)] public sealed class LabelAttribute : Attribute { public LabelAttribute(String labelName) { Name = labelName; } public String Name { get; set; } } |
我想得到属性的字段:
1 2 3 4 5 6 7 8 9 | public enum ECategory { [Label("Safe")] Safe, [Label("LetterDepositBox")] LetterDepositBox, [Label("SavingsBookBox")] SavingsBookBox, } |
读取ecategory.safe label属性值:
1 2 3 4 |
1 2 3 4 5 6 7 8 9 10 | 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); |
然后,您可以检索每个值的标签,如下所示:
1 | var label = fieldsMap[ECategory.Safe]; |
您可以创建扩展名:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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; } } |
然后你可以做:
1 2 | var category = ECategory.Safe; var labelValue = category.GetLabel(); |