【问题标题】:How to use enum item name which contains space? [duplicate]如何使用包含空格的枚举项目名称? [复制]
【发布时间】:2016-01-11 03:41:55
【问题描述】:

如何使用包含空格的枚举项名称?

enum Coolness
{
    Not So Cool = 1,
    VeryCool = 2,
    Supercool = 3
}

我通过以下代码获取枚举项名称

string enumText = ((Coolness)1).ToString()

我不会更改此代码,但上面的代码应该返回 Not So Cool。 有没有使用 oops 概念来实现这一点? 这里我不想更改检索语句。

【问题讨论】:

  • 去掉空格,它们不酷
  • 没错,不可能有带空格的枚举成员。
  • 也许你需要enums with strings
  • 您可以添加一个包含空格的DescriptionAttribute
  • 看看这个答案,以便为枚举添加描述以及如何检索这些友好名称:stackoverflow.com/a/1415187/1666620

标签: c# .net oop enums


【解决方案1】:

在你的枚举中避免space

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);

【讨论】:

  • 我不会这样。这里 enumText 将是“NotSocool”,但我想要“Not So Cool”
  • 我已经编辑了我的答案,看看我的编辑。
  • 是的,你是对的,这样它会起作用..但在这里我不想改变这个语句代码字符串 enumText = ((Coolness)1).ToString() 虽然它应该给我想要的答案。
  • 是否可以用 displayName 替换描述?
【解决方案2】:

使用Display attributes:

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();
}

(归功于帮助者Hrvoje Stanisic

【讨论】:

  • 我试过这种方式,但是 string enumText = ((Coolness)1).ToString() 这个输出是“NotSoCool”
  • 这篇文章stackoverflow.com/questions/13099834/… 有一个你可以使用的枚举助手。试试看。
  • 这里不想改这个语句代码字符串 enumText = ((Coolness)1).ToString()
  • 好吧,在这种情况下,您唯一的选择是覆盖 ToString 并使其执行类似 return EnumHelper.GetDisplayValue((Coolness)1); 的操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多