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

发布于 2024-12-10 20:58:19 字数 1181 浏览 0 评论 0原文

可能的重复:
是否有一个简单的脚本可以将 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);
}

Possible Duplicate:
Is there a simple script to convert C++ enum to string?

In the C# program below, while using enumeration Priority, i need the string "None" and not the id 0. The C# code for doing this is given below. Is there an elegant way of doing this in C++. Can a map be avoided in the C++ implementation.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不弃不离 2024-12-17 20:58:19

在 C++ 中,枚举只不过是围绕整数文字的一些语法糖。编译器会快速删除枚举器名称,因此运行时永远无法访问它。如果你想要一个枚举的字符串名称,你必须以困难的方式做到这一点。

In C++, an enum is nothing more than a bit of syntactic sugar around an integral literal. The compiler quickly strips the enumerator name away, so the runtime never has access to it. If you want to have a string name for an enum, you have to do it the hard way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文