从枚举值中获取字符串的优雅方法?

Mar*_*tin 0 c# c++ enums

可能重复:
是否有一个简单的脚本将C++枚举转换为字符串?

在下面的C#程序中,使用枚举优先级时,我需要字符串"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);
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 5

在C++中,枚举只不过是一个整数字面上的一些语法糖.编译器会快速剥离枚举器名称,因此运行时永远无法访问它.如果你想拥有枚举的字符串名称,你必须以艰难的方式去做.