码迷,mamicode.com
首页 > Windows程序 > 详细

在C#中如何读取枚举值的描述属性

时间:2014-11-26 22:25:51      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:des   io   os   sp   on   div   cti   bs   ad   

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

在C#中如何读取枚举值的描述属性

标签:des   io   os   sp   on   div   cti   bs   ad   

原文地址:http://www.cnblogs.com/xiaofengfeng/p/4125003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!