您的位置:首页 > 其它

获取枚举的描述

2016-08-30 00:00 197 查看
摘要: 通过反射的方式获取枚举元素的描述特性

引用
System.ComponentModel
为枚举中的元素设置Description特性

public enum PublishState
{
[Description("信息置顶")]
Top = 1,
[Description("信息审核")]
Approve,
[Description("信息反审核")]
Disapprove,
[Description("信息删除")]
Remove
}

利用反射的方式,去获取枚举元素的特性

public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  获取枚举的描述