How to define and use enum types in C#?
In C#, enumeration type is a data type used to define a collection of named constants. Enumerations are commonly employed to represent a group of related constants, enhancing the readability and maintainability of code.
Here is an example of defining and using an enum type in C#:
// 定义一个枚举类型
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
// 使用枚举类型
DaysOfWeek today = DaysOfWeek.Monday;
// 输出枚举值
Console.WriteLine(today); // 输出 Monday
// 使用 switch 语句处理枚举类型
switch (today)
{
case DaysOfWeek.Monday:
Console.WriteLine("Today is Monday");
break;
case DaysOfWeek.Tuesday:
Console.WriteLine("Today is Tuesday");
break;
// 其他枚举值的处理
default:
Console.WriteLine("Today is not Monday or Tuesday");
break;
}
By defining an enum type, constant values in the code can be represented more clearly and improve the readability and maintainability of the code. When using an enum type, it can be assigned, compared, and processed just like other data types.