How to access integer and string of enum type?

蹲街弑〆低调 提交于 2021-01-29 04:59:47

问题


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

Dentist (2533)

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

回答1:


It sounds like you want something like:

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

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



回答2:


You can also use the format strings g, G, f, F to print the name of the enumeration entry, or d and D to print the decimal representation:

var dentist = eOccupationCode.Dentist;

Console.WriteLine(dentist.ToString("G"));     // Prints: "Dentist"
Console.WriteLine(dentist.ToString("D"));     // Prints: "2533"

... or as handy one-liner:

Console.WriteLine("{0:G} ({0:D})", dentist);  // Prints: "Dentist (2533)"

This works with Console.WriteLine, just as with String.Format.




回答3:


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

Without casting, it would output the enum identifier: Dentist

If you need to access that enum value you need to cast it:

int value = (int)eOccupationCode.Dentist;



回答4:


I guess you mean this

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


来源:https://stackoverflow.com/questions/15946954/how-to-access-integer-and-string-of-enum-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!