C# 中带有自定义值的枚举
csharpprogrammingserver side programming更新于 2025/11/24 5:04:00
枚举是用于存储一组命名常量(如年份、产品、月份、季节等)的枚举。
枚举常量的默认值从 0 开始并递增。它具有固定的常量集,可以轻松遍历。但是,您仍然可以更改起始索引并使用您选择的值对其进行自定义。
在下面的示例中,我将自定义值设置为 20,而不是默认值 0。
示例
using System;
public class Demo {
public enum Vehicle { Car =20, Motorcycle, Bus, Truck }
public static void Main() {
int a = (int)Vehicle.Car;
int b = (int)Vehicle.Motorcycle;
int c = (int)Vehicle.Bus;
int d = (int)Vehicle.Truck;
Console.WriteLine("Car = {0}", a);
Console.WriteLine("Motorcycle = {0}", b);
Console.WriteLine("Bus = {0}", c);
Console.WriteLine("Truck = {0}", d);
}
}
输出
Car = 20 Motorcycle = 21 Bus = 22 Truck = 23

