使用用户友好的字符串枚举 ToString [英] Enum ToString with user friendly strings
本文介绍了使用用户友好的字符串枚举 ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的枚举由以下值组成:
My enum consists of the following values:
private enum PublishStatusses{
NotCompleted,
Completed,
Error
};
不过,我希望能够以用户友好的方式输出这些值.
我不需要能够再次从字符串到值.
I want to be able to output these values in a user friendly way though.
I don't need to be able to go from string to value again.
推荐答案
我使用 Description
属性来自 System.ComponentModel 命名空间.简单地装饰枚举:
I use the Description
attribute from the System.ComponentModel namespace. Simply decorate the enum:
private enum PublishStatusValue
{
[Description("Not Completed")]
NotCompleted,
Completed,
Error
};
然后使用此代码检索它:
Then use this code to retrieve it:
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();
}
这篇关于使用用户友好的字符串枚举 ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文