具有自定義值在 C# 中列舉


列舉是對命名常量(如年、產品、月份、季等)進行儲存的一種列舉方式。

列舉常量的預設值從 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

更新於: 23-6 月-2020

2K+ 瀏覽次數

助力您的 事業

完成課程認證

開始學習
廣告
© . All rights reserved.