0

什么 C# 代码将为下面的枚举类型的变量输出以下内容?

牙医 (2533)

public enum eOccupationCode
        {
             Butcher = 2531,
             Baker = 2532,
             Dentist = 2533,
             Podiatrist = 2534,
             Surgeon = 2535,
             Other = 2539
        }
4

4 回答 4

7

听起来你想要这样的东西:

// Please drop the "e" prefix...
OccupationCode code = OccupationCode.Dentist;

string text = string.Format("{0} ({1})", code, (int) code);
于 2013-04-11T10:57:59.413 回答
7

您还可以使用格式字符串 g, G, f,F来打印枚举条目的名称,或者d打印D十进制表示:

var dentist = eOccupationCode.Dentist;

Console.WriteLine(dentist.ToString("G"));     // Prints: "Dentist"
Console.WriteLine(dentist.ToString("D"));     // Prints: "2533"

...或方便的单线:

Console.WriteLine("{0:G} ({0:D})", dentist);  // Prints: "Dentist (2533)"

这适用于Console.WriteLine,就像String.Format.

于 2013-04-11T11:03:41.060 回答
2

What C# code would output the following for a variable of the enum type below?

如果不进行强制转换,它将输出枚举标识符:Dentist

如果您需要访问该枚举值,则需要强制转换它:

int value = (int)eOccupationCode.Dentist;
于 2013-04-11T10:59:30.963 回答
0

我猜你的意思是这个

eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)
于 2013-04-11T11:00:13.357 回答