2012-11-09 84 views
3

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

回答

2

閱讀ECategory.Safe標籤屬性值:

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

我想你在功能中缺少參數名 –

+0

@PaoloTedesco固定 – Default

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