如何使用DescriptionAttibute
通过enums
实现以下功能?请注意枚举值中的空格。
public enum PersonGender
{
Unknown = 0,
Male = 1,
Female = 2,
Intersex = 3,
Indeterminate = 3,
Non Stated = 9,
Inadequately Described = 9
}
答案 0 :(得分:3)
例如,你可以这样使用:
这是我们的枚举:
public enum MyEnum
{
[Description("Description for Foo")]
Foo,
[Description("Description for Bar")]
Bar
}
我们获取属性的方法。
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
}
你可以得到描述:
MyEnum x = MyEnum.Foo;
string description = x.GetDescription();