C#的枚举
枚举是由程序员定义的,与类或结构体一样。
- 枚举通常是值类型,因此可以直接存出它们的数据;
- 枚举只有一种类型的成员:命名的整数值常量。在默认情况下,编译器对第一个成员赋值0(自己也可以手动设定),对每一个后续成员的赋值依次递增。
namespace CSharpProject1;
class Program
{
static void Main(string[] args)
{
TrafficLight green = TrafficLight.Green;
TrafficLight yellow = TrafficLight.Yellow;
TrafficLight red = TrafficLight.Red;
Console.WriteLine($"{green}\t{(int)green}");
Console.WriteLine($"{yellow}\t{(int)yellow}");
Console.WriteLine($"{red}\t{(int)red}");
}
}
enum TrafficLight
{
Green,
Yellow,
Red
}
结果如下所示:
D:/RiderProjects/CSharpProject1/CSharpProject1/bin/Debug/net8.0/CSharpProject1.exe
Green 0
Yellow 1
Red 2
Process finished with exit code 0.
标签:Console,C#,TrafficLight,yellow,int,枚举,CSharpProject1
From: https://www.cnblogs.com/lilyflower/p/17958499