public static string ToDescription(this Enum enumeration)
{
Type type = enumeration.GetType();
MemberInfo[] memInfo = type.GetMember(enumeration.ToString());
if (null != memInfo && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (null != attrs && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return enumeration.ToString();
}
public enum AssessmentAnswer
{
[DescriptionAttribute("强烈的反对")]
Strongly_Disagree = 1,
[DescriptionAttribute("反对")]
Disagree = 2,
Neutral = 3,
Agree = 4,
[DescriptionAttribute("完全的同意")]
Strongly_Agree = 5
}
当要获取描述语句时, 你可以轻松的调用ToDescription :
//返回 "强烈的反对"
AssessmentAnswer.Strongly_Disagree.ToDescription()
注意, 如果没有给元素加入特性, 你仍旧可以使用ToDescription, 可以参考上面的代码看看是为什么.
//返回 “Disagree”
AssessmentAnswer.Disagree.ToDescription()
代码来源于博客园,自己整理待用!