.NET获取枚举值的描述
.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 );