📜  枚举 c# (1)

📅  最后修改于: 2023-12-03 14:55:31.674000             🧑  作者: Mango

Enumerations in C#

Introduction

In programming, an enumeration is a data type that consists of a set of named values. This type of data structure is often used to represent a set of predefined constants or options. In C#, enumerations are defined using the enum keyword.

Basic syntax

The basic syntax for declaring an enumeration consists of the enum keyword followed by the name of the enumeration and a list of comma-separated values enclosed in curly braces:

enum DaysOfWeek {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

In this example, we define an enumeration named DaysOfWeek that contains seven values representing days of the week. By default, the underlying type of an enumeration is int, so the first value is assigned the integer value 0, the second value is assigned 1, and so on.

Using enumerations

Once an enumeration is defined, you can use its values in your program by referencing them using the enumeration name:

DaysOfWeek today = DaysOfWeek.Wednesday;

In this example, we declare a variable today of type DaysOfWeek and assign it the value Wednesday.

In addition to assigning individual values, you can also use the enum keyword in switch statements:

switch (today) {
  case DaysOfWeek.Monday:
    Console.WriteLine("It's Monday.");
    break;
  case DaysOfWeek.Tuesday:
    Console.WriteLine("It's Tuesday.");
    break;
  // ...
}
Enum underlying types

As mentioned earlier, the default underlying type of an enumeration is int. However, you can specify a different underlying type by explicitly specifying the type after the enumeration name:

enum Difficulty : byte {
  Easy,
  Medium,
  Hard
}

In this example, we define an enumeration named Difficulty with an underlying type of byte. This means that the first value, Easy, is assigned the byte value 0, the second value is assigned 1, and so on.

Conclusion

Enumerations are a powerful feature of C# that allow you to represent sets of named values. They can make your code more readable and maintainable, and are especially useful in situations where you need to represent a set of predefined options or constants.