在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