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

时间:2013-04-11 10:56:38

标签: c# .net string enums

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

  

牙医(2533)

public enum eOccupationCode
        {
             Butcher = 2531,
             Baker = 2532,
             Dentist = 2533,
             Podiatrist = 2534,
             Surgeon = 2535,
             Other = 2539
        }

4 个答案:

答案 0 :(得分:7)

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

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

string text = string.Format("{0} ({1})", code, (int) code);

答案 1 :(得分:7)

您还可以使用format strings gGfF来打印枚举条目的名称,或{{1} }和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一样。

答案 2 :(得分:2)

What C# code would output the following for a variable of the enum type below?

如果没有强制转换,它会输出枚举标识符:Dentist

如果您需要访问该枚举值,则需要将其强制转换:

int value = (int)eOccupationCode.Dentist;

答案 3 :(得分:0)

我猜你的意思是这个

eOccupationCode code = eOccupationCode.Dentist;
Console.WriteLine(string.Format("{0} ({1})", code,(int)code));
// outputs Dentist (2533)