在C#中,有時候我們需要讀取枚舉值的描述屬性,也就是說這個枚舉值代表了什么意思。比如本文中枚舉值 Chinese ,我們希望知道它代表意思的說明(即“中文”)。
有下面的枚舉:
1
2
3
4
5
6
|
public
enum
EnumLanugage
{
[System.ComponentModel.Description(
"中文"
)]
Chinese,
English
}
|
我們要獲取的就是 Chinese 中的說明文字“中文”。
1
2
3
4
5
6
7
8
9
|
public
string
GetEnumDescription(Enum enumValue)
{
string
str = enumValue.ToString();
System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
object
[] objs = field.GetCustomAttributes(
typeof
(System.ComponentModel.DescriptionAttribute),
false
);
if
(objs ==
null
|| objs.Length == 0)
return
str;
System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
return
da.Description;
}
|
調用 GetEnumDescription(EnumLanguage.Chinese) 后 將返回“中文”,如果換成 EnumLanguage.English ,由於在 English 上沒有定義 Description ,將直接返回枚舉名稱 English 。