问题
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