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

标签 c# c++ enums

<分区>

Possible Duplicate:
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);
}

最佳答案

在 C++ 中,枚举只不过是整数文字周围的一点语法糖。编译器会迅速去除枚举器名称,因此运行时永远无法访问它。如果您想为枚举使用字符串名称,则必须采取艰难的方式。

关于c# - 从枚举值中获取字符串的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7802683/

相关文章:

c# - Azure 事件日志 - TargetInitationException 和奇怪的消息

c# - WPF DataGrid - 编辑结束后单元格的新值

c# - 发送一个 JSON 数组以作为 Dictionary<string,string> 接收

java - 为什么我不能用接口(interface)返回枚举?

java - 从返回枚举的接口(interface)检索数据

swift - 使用枚举登录

c# - 使 Refit 自动在查询字符串中提供参数

c++ - 从其处理程序或处理程序 dtor 中销毁 boost::asio 计时器是否安全?

c++ - 函数指针(指向其他内核)作为 CUDA 中的内核 arg

c++ - 为什么在实现单例类时得到 "Undefined reference error"?