【问题标题】:An elegant way to get string from enum value? [duplicate]从枚举值获取字符串的优雅方法? [复制]
【发布时间】:2011-12-09 19:14:51
【问题描述】:

可能重复:
Is there a simple script to convert C++ enum to string?

在下面的 C#program 中,使用枚举优先级时,我需要字符串“None”而不是 id 0。下面给出了执行此操作的 C# 代码。在 C++ 中是否有一种优雅的方式来做到这一点。在 C++ 实现中可以避免映射吗?

enum Priority
{
    None,
    Trivial,
    Normal,
    Important,
    Critical
}

class Program
{
    static void Main()
    {
    // Write string representation for Important.
    Priority enum1 = Priority.Important;
    string value1 = enum1.ToString();

    // Loop through enumerations and write string representations. (See GetNames)
    for (Priority enum2 = Priority.None; enum2 <= Priority.Critical; enum2++)
    {
        string value2 = enum2.ToString();
        Console.WriteLine(value2); //outputs the string None, Trivial etc ...
    }
    }
}

public override string ToString()
{
    Type type = base.GetType();
    object obj2 = ((RtFieldInfo)GetValueField(type)).InternalGetValue(this, false);
    return InternalFormat(type, obj2);
}

【问题讨论】:

  • 最后一段代码是什么?样本似乎没有必要......
  • 我投票给了欺骗问题,但我不喜欢接受的答案。该页面上有很多有用的答案,包括问题本身的答案。
  • @MerlynMorgan-Graham:我同意你接受的答案。
  • @MerlynMorgan-Graham:我修正了我的评论,抱歉,我猜我今天的大脑不太清醒。

标签: c# c++ enums


【解决方案1】:

在 C++ 中,枚举只不过是整数文字周围的一些语法糖。编译器迅速剥离枚举器名称,因此运行时永远无法访问它。如果你想为一个枚举指定一个字符串名称,你必须努力做到这一点。

【讨论】:

  • +1,尽管在 整体文字 周围写 ... 语法糖而不是 ... 语法会更好整数周围的糖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 2013-07-18
  • 1970-01-01
  • 2020-07-11
  • 2021-04-04
  • 2020-12-24
  • 2014-07-20
相关资源
最近更新 更多