C# 列舉 GetName 方法


GetNames() 返回列舉中常量名稱的陣列。

下面是列舉。

enum Stock { Watches, Books, Grocery };

要獲取名稱陣列,請使用 GetNames() 並迴圈瀏覽,如下所示 −

foreach(string s in Enum.GetNames(typeof(Stock))) {
}

讓我們現在看看完整的示例。

示例

 線上演示

using System;
class Demo {
   enum Stock { Watches, Books, Grocery };
   static void Main() {
      Console.WriteLine("The value of first stock category = {0}",Enum.GetName(typeof(Stock), 0));
      Console.WriteLine("The value of second stock category = {0}",Enum.GetName(typeof(Stock), 1));
      Console.WriteLine("The value of third stock category = {0}",Enum.GetName(typeof(Stock), 2));
      Console.WriteLine("All the categories of stocks...");
      foreach(string s in Enum.GetNames(typeof(Stock))) {
         Console.WriteLine(s);
      }
   }
}

輸出

The value of first stock category = Watches
The value of second stock category = Books
The value of third stock category = Grocery
All the categories of stocks...
Watches
Books
Grocery

更新時間: 23-Jun-2020

933 次瀏覽

開啟您的 職業

完成課程並獲得認證

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