← 從零開始學 C#
第 36 課,共 39 課 · 10 XP
列舉 (enum)
理論與題目說明
機器翻譯,尚未經母語人士審閱。
enum 是一組有名字的常數。用 state == State.Running 取代 state == 2 這種「魔術」數字:
enum Direction { North, East, South, West } // 0, 1, 2, 3
Direction d = Direction.East;
Console.WriteLine(d); // East——輸出的是名字
Console.WriteLine((int)d); // 1
d = (Direction)(((int)d + 1) % 4); // South——順時針轉四分之一圈
Direction e = Enum.Parse<Direction>("West");
switch (d)
{
case Direction.North: y++; break;
…
}
- 值也可以明確指定:
enum Level { Easy = 1, Hard = 10 }; Enum.GetValues<Direction>()給你所有的值,用在迴圈裡很方便。
題目。 機器人站在 (0, 0),面向 North(北是 y+1,東是 x+1)。指令在一行裡:
L——向左轉、R——向右轉、F——往前一步。輸出 x y 方向。