如何使用代碼?
對每一個enum枚舉都添加一個Description屬性:
private enum MyColors
{
[Description("yuk!")] LightGreen = 0x012020,
[Description("nice :-)")] VeryDeepPink = 0x123456,
[Description("so what")] InvisibleGray = 0x456730,
[Description("no comment")] DeepestRed = 0xfafafa,
[Description("I give up")] PitchBlack = 0xffffff,
}
為了在代碼中讀取描述字符串,你可以如下這麼做:
public static string GetDescription(Enum value)
{
FieldInfo fi= value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length>0)?attributes[0].Description:value.ToString();
} www.2cto.com
如果沒有下面的using語句,你的代碼是不能通過編譯的。
using System.ComponentModel;
using System.Reflection;