Enum คือการแจงนับเพื่อเก็บชุดของค่าคงที่ที่มีชื่อ เช่น ปี ผลิตภัณฑ์ เดือน ฤดูกาล เป็นต้น
ค่าเริ่มต้นของค่าคงที่ Enum เริ่มต้นจาก 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