如何获取枚举的属性
可能重复:
获得Enum价值的属性
这是我的class级:
[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, }
阅读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;
您可以创建扩展:
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();
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() .Fist().Name }) .ToDictionary(f => f.Value, f => f.Label);
之后,您可以检索每个值的标签,如下所示:
var label = fieldsMap[ECategory.Safe];