如何访问整数和枚举类型的字符串?

CJ7*_*CJ7 0 .net c# string enums

对于下面的枚举类型的变量,C#代码将输出以下内容?

牙医(2533)

public enum eOccupationCode
        {
             Butcher = 2531,
             Baker = 2532,
             Dentist = 2533,
             Podiatrist = 2534,
             Surgeon = 2535,
             Other = 2539
        }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

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

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

string text = string.Format("{0} ({1})", code, (int) code);
Run Code Online (Sandbox Code Playgroud)

  • 是的,他应该删除"e"前缀 (2认同)

Car*_*ten 7

您也可以使用格式字符串 g,G,f,F打印枚举条目的名称,或dD打印十进制表示:

var dentist = eOccupationCode.Dentist;

Console.WriteLine(dentist.ToString("G"));     // Prints: "Dentist"
Console.WriteLine(dentist.ToString("D"));     // Prints: "2533"
Run Code Online (Sandbox Code Playgroud)

......或者作为方便的单行程:

Console.WriteLine("{0:G} ({0:D})", dentist);  // Prints: "Dentist (2533)"
Run Code Online (Sandbox Code Playgroud)

这适用于Console.WriteLine,就像使用一样String.Format.