在C#中如何讀取枚舉值的描述屬性


在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 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM