大佬教程收集整理的这篇文章主要介绍了带有用户友好字符串的Enum ToString,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Description
System.ComponentModel命名空间中的属性。只需装饰枚举即可:
private enum PublishStatusValue
{
[Description("Not Completed")]
NotCompleted,
Completed,
Error
};
然后使用以下代码进行检索:
public static String GetDescription<T>(this T enumerationvalue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new Argumentexception("EnumerationValue must be of Enum type", "enumerationValue");
}
//TrIEs to find a DescriptionAttribute for a potential frIEndly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttributE), falsE);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttributE)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
我的枚举包含以下值:
private enum PublishStatusses{
NotCompleted,Completed,Error
};
我希望能够以用户友好的方式输出这些值。
我不需要再次从字符串变为值。
以上是大佬教程为你收集整理的带有用户友好字符串的Enum ToString全部内容,希望文章能够帮你解决带有用户友好字符串的Enum ToString所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。