什麼C#代碼將輸出下面的枚舉類型的變量以下?如何訪問枚舉類型的整數和字符串?
牙醫(2533)
public enum eOccupationCode
{
Butcher = 2531,
Baker = 2532,
Dentist = 2533,
Podiatrist = 2534,
Surgeon = 2535,
Other = 2539
}
什麼C#代碼將輸出下面的枚舉類型的變量以下?如何訪問枚舉類型的整數和字符串?
牙醫(2533)
public enum eOccupationCode
{
Butcher = 2531,
Baker = 2532,
Dentist = 2533,
Podiatrist = 2534,
Surgeon = 2535,
Other = 2539
}
這聽起來像你想要的東西,如:
// Please drop the "e" prefix...
OccupationCode code = OccupationCode.Dentist;
string text = string.Format("{0} ({1})", code, (int) code);
What C# code would output the following for a variable of the enum type below?
沒有鑄造,它會輸出枚舉標識符:Dentist
如果您需要訪問你需要投它是枚舉值:
int value = (int)eOccupationCode.Dentist;
你能幫忙解釋爲什麼這是默認值,並且使用枚舉值不是默認值嗎? – 2018-01-10 19:07:44
我猜你的意思是這
eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)
ToString是多餘的。 – 2013-04-11 11:19:05
您還可以使用format stringsg
,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
。
是的,他真的應該放棄「e」前綴 – 2013-04-11 11:13:09