GetNames() ส่งกลับอาร์เรย์ของชื่อของค่าคงที่ในการแจงนับ
ต่อไปนี้คือ enum
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