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
广告