如何使用包含空格的枚举项目名称
本文关键字:项目 枚举 何使用 包含 空格 | 更新日期: 2023-09-27 18:17:31
如何使用包含空格的enum项目名称?
enum Coolness
{
Not So Cool = 1,
VeryCool = 2,
Supercool = 3
}
我正在通过下面的代码获得Enum项目名称
string enumText = ((Coolness)1).ToString()
我不想改变这段代码,但上面的代码应该返回Not So Cool。是否有使用oops概念来实现这一点?这里我不想改变检索语句
使用显示属性:
enum Coolness : byte
{
[Display(Name = "Not So Cool")]
NotSoCool = 1,
VeryCool = 2,
Supercool = 3
}
你可以使用这个帮助器来获取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();
}
(Credit to Hrvoje Stanisic for the Helper)
避免在enum上使用space
enum Coolness : int
{
NotSoCool = 1,
VeryCool = 2,
Supercool = 3
}
要获取文本形式的值,尝试如下:
string enumText = ((Coolness)1).ToString()
如果您希望对enum的每个项都有一个友好的描述,请尝试使用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);