【发布时间】: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:我修正了我的评论,抱歉,我猜我今天的大脑不太清醒。