對於.net Framework中內置的幾種集合類,foreach是一種很方便的遍歷方式:
1、非泛型&弱類型的Collections(ArrayList,Queue,Stack):
使用object:
ArrayList al = new ArrayList();
al.Add("hello");
al.Add(1);
foreach(object obj in al)
{
Console.WriteLine(obj.ToString());
}
如果確定ArrayList中的類型的話,也可以用這個類型代理,會自動強轉,但若轉換不成功,拋出InvalidCastException。
ArrayList al = new ArrayList();
al.Add("hello");
al.Add("world");
foreach(string s in al)
{
Console.WriteLine(s);
}
2、強類型的Collections(StringCollection和BitArray),可分別使用string和bool而無需強轉。
非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):
使用DictionaryEntry:
Hashtable ht = new Hashtable();
ht.Add(1, "Hello");
ht.Add(2, "World");
foreach (DictionaryEntry de in ht)
{
Console.WriteLine(de.Value);
}
特殊的Dictionary(NameValueCollection):
不能直接對NameValueCollection進行foreach遍歷,需要兩級:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("a", "Hello");
nvc.Add("a", "World");
nvc.Add("b", "!");
foreach (string key in nvc.AllKeys)
{
foreach (string value in nvc.GetValues(key))
{
Console.WriteLine(value);
}
}
泛型Collections
List<T>,Queue<T>,Stack<T>: 這個好說,foreach T 就可以了。
Dictionary<Tkey,TValue>和SortedList<Tkey,TValue> 要使用KeyValuePair<Tkey,TValue>:
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "Hello");
dic.Add(2, "World");
foreach(KeyValuePair<int,string> pair in dic)
{
Console.WriteLine(pair.Value);
}
注意 : 在foreach過程中,集合類長度的改變會導致錯誤,因此foreach的循環體中不要有對集合類的增減操作。而Dictionary<Tkey,TValue>是非線程安全的,多線程時對其使用foreach可能會引起錯誤,多線程時推薦使用非泛型的Hashtable(或者自己lock..)。