什么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