如何访问enum类型的整数和字符串
本文关键字:类型 整数 字符串 enum 何访问 访问 | 更新日期: 2023-09-27 18:08:51
对于下面枚举类型的变量,哪些c#代码会输出以下内容?
牙医(2533)
public enum eOccupationCode
{
Butcher = 2531,
Baker = 2532,
Dentist = 2533,
Podiatrist = 2534,
Surgeon = 2535,
Other = 2539
}
您也可以使用格式字符串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
。
听起来你想要这样做:
// 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
如果需要访问该enum值,则需要对其进行强制类型转换:
int value = (int)eOccupationCode.Dentist;
我猜你是这个意思
eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)