从枚举值获取字符串的优雅方法?
在下面的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 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.