问题
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