C# 如何使用包含空格的枚举项名称?
如何使用包含空格的枚举项名称C# 如何使用包含空格的枚举项名称?,c#,.net,oop,enums,C#,.net,Oop,Enums,如何使用包含空格的枚举项名称 enum Coolness { Not So Cool = 1, VeryCool = 2, Supercool = 3 } 我通过下面的代码获取枚举项名称 string enumText = ((Coolness)1).ToString() 我不想修改这段代码,但上面的代码应该不会太酷。 有没有使用oops概念来实现这一点? 这里我不想更改检索语句。避免枚举上的空格 enum Coolness : int { NotSoCool
enum Coolness
{
Not So Cool = 1,
VeryCool = 2,
Supercool = 3
}
我通过下面的代码获取枚举项名称
string enumText = ((Coolness)1).ToString()
我不想修改这段代码,但上面的代码应该不会太酷。
有没有使用oops概念来实现这一点?
这里我不想更改检索语句。避免枚举上的
空格
enum Coolness : int
{
NotSoCool = 1,
VeryCool = 2,
Supercool = 3
}
要获取文本中的值,请尝试以下操作:
string enumText = ((Coolness)1).ToString()
如果要为枚举的每个项提供友好的描述,请尝试使用description
属性作为示例:
enum Coolness : int
{
[Description("Not So Cool")]
NotSoCool = 1,
[Description("Very Cool")]
VeryCool = 2,
[Description("Super Cool")]
Supercool = 3
}
要读取此属性,可以使用如下方法:
public class EnumHelper
{
public static string GetDescription(Enum @enum)
{
if (@enum == null)
return null;
string description = @enum.ToString();
try
{
FieldInfo fi = @enum.GetType().GetField(@enum.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
description = attributes[0].Description;
}
catch
{
}
return description;
}
}
并使用它:
string text = EnumHelper.GetDescription(Coolness.SuperCool);
使用:
您可以使用此帮助程序获取DisplayName
public static string GetDisplayValue(T value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}
(感谢帮助者)删除空格,它们不可合并,这是不可能的。要让enum memebers与空格一起使用。也许你需要添加一个包含空格的DescriptionAttribute
。看看这个答案,以便为enum添加说明以及如何检索这些友好名称:我不会这样做。这里的enumText将是“NotSoCool”,但我想要“不那么酷”我已经编辑了我的anwser,看看我的编辑。是的,你是对的,这样它会工作。。但是在这里我不想更改这个语句代码字符串enumText=((Coolness)1).ToString(),虽然它应该会给我想要的答案。是否可以用displayName替换描述?我尝试了这种方法,但是字符串enumText=((Coolness)1.ToString()这个输出是“NotSoCool”。这篇文章有一个enum助手,你可以使用。试试看。这里我不想更改这个语句代码字符串enumText=((Coolness)1).ToString(),在这种情况下,您唯一的选择是重写ToString
,并使其执行类似于返回EnumHelper.GetDisplayValue((Coolness)1)的操作代码>
public static string GetDisplayValue(T value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes == null) return string.Empty;
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
}