How to use enum types in C#?
In C#, enums are a special data type used to represent a group of related named constants. Enums can be used in a program to better clarify specific values in the code.
Here are some common methods using enum types:
- Declaration of an enumeration type:
enum DaysOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
- Use values of enumeration type.
DaysOfWeek today = DaysOfWeek.Monday;
Console.WriteLine(today); // 输出 Monday
- Compare values using an enum type:
DaysOfWeek today = DaysOfWeek.Wednesday;
if (today == DaysOfWeek.Wednesday) {
Console.WriteLine("今天是星期三");
}
- Use enumerated values for branch selection in a switch statement.
DaysOfWeek today = DaysOfWeek.Tuesday;
switch (today) {
case DaysOfWeek.Monday:
Console.WriteLine("今天是星期一");
break;
case DaysOfWeek.Tuesday:
Console.WriteLine("今天是星期二");
break;
// ...
default:
Console.WriteLine("今天不是工作日");
break;
}
- Passing or returning enumerated values as method parameters.
DaysOfWeek GetNextDay(DaysOfWeek currentDay) {
if (currentDay == DaysOfWeek.Sunday) {
return DaysOfWeek.Monday;
}
else {
return (DaysOfWeek)((int)currentDay + 1);
}
}
DaysOfWeek tomorrow = GetNextDay(DaysOfWeek.Tuesday);
Console.WriteLine(tomorrow); // 输出 Wednesday
- Obtain the string representation of an enumeration type.
DaysOfWeek today = DaysOfWeek.Thursday;
string dayString = today.ToString();
Console.WriteLine(dayString); // 输出 Thursday
Using enumeration types can make code more readable and maintainable because they provide a more intuitive way to represent a set of related constant values.