2013-04-11 52 views

回答

7

这听起来像你想要的东西,如:

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

string text = string.Format("{0} ({1})", code, (int) code); 
+2

是的,他真的应该放弃“e”前缀 – 2013-04-11 11:13:09

2

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

没有铸造,它会输出枚举标识符:Dentist

如果您需要访问你需要投它是枚举值:

int value = (int)eOccupationCode.Dentist; 
+0

你能帮忙解释为什么这是默认值,并且使用枚举值不是默认值吗? – 2018-01-10 19:07:44

0

我猜你的意思是这

eOccupationCode code = eOccupationCode.Dentist; 
Console.WriteLine(string.Format("{0} ({1})", code,(int)code)); 
// outputs Dentist (2533) 
+0

ToString是多余的。 – 2013-04-11 11:19:05

7

您还可以使用format stringsgGfF到打印枚举条目的名称或dD以打印十进制表示法:

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