技术探索

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

2013-07-30
2491

在C#中,有时候我们需要读取枚举值的描述属性,也就是说这个枚举值代表了什么意思。比如本文中枚举值 Chinese ,我们希望知道它代表意思的说明(即“中文”)。

 

有下面的枚举:

public enum EnumLanugage
{
    [System.ComponentModel.Description("中文")]
    Chinese,
    English
}

 

我们要获取的就是 Chinese 中的说明文字“中文”。

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 。