.NET获取枚举DescriptionAttribute描述信息性能改进的多种方法

2019-05-22 21:25:11刘景俊

ps:.NET获取枚举值的描述

一、给枚举值定义描述的方式

public enum TimeOfDay 
{ 
[Description("早晨")] 
Moning = 1, 
[Description("下午")] 
Afternoon = 2, 
[Description("晚上")] 
Evening = 3, 
} 

二、获取枚举值的描述的方法

public static string GetDescriptionFromEnumValue(Type enumType, object enumValue)
{
try
{
object o = Enum.Parse(enumType, enumValue.ToString());
string name = o.ToString();
DescriptionAttribute[] customAttributes = (DescriptionAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((customAttributes != null) && (customAttributes.Length == 1))
{
return customAttributes[0].Description;
}
return name;
}
catch
{
return "未知";
}
}

三、获取枚举值的描述的方法的使用

string strMoning = GetDescriptionFromEnumValue( typeof (TimeOfDay) , 2 );