如何:循环访问集合 (Visual C#)
更新:2007 年 11 月
本示例使用 Hashtable 类中的 Add 方法向 Hashtable 集合中添加项。然后使用 foreach 语句循环访问该集合。
示例
Hashtable phones = new Hashtable();
// Add items.
phones.Add("John", "555-0150");
phones.Add("Enju", "555-0199");
phones.Add("Molly", "555-0151");
phones.Add("James", "555-0142");
phones.Add("Ahmed", "555-0128");
phones.Add("Leah", "555-0100");
// Iterate through the collection.
System.Console.WriteLine("Name\t\tNumber");
foreach (string name in phones.Keys)
{
System.Console.WriteLine(name +"\t"+ phones[name]);
}
编译代码
复制该代码,并将其粘贴到控制台应用程序的 Main 方法中。
将一个 using 指令添加到 System.Collections 命名空间中。