2013-04-11 53 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