发表于: other | 作者: | 日期: 2013/8/07 12:08

对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:
非泛型&弱类型的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);
}

强类型的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,Queue,Stack: 这个好说,foreach T 就可以了。
Dictionary和SortedList 要使用KeyValuePair:

Dictionary dic = new Dictionary();
dic.Add(1, “Hello”);
dic.Add(2, “World”);
foreach(KeyValuePair pair in dic)
{
Console.WriteLine(pair.Value);
}

注意 : 在foreach过程中,集合类长度的改变会导致错误,因此foreach的循环体中不要有对集合类的增减操作。而Dictionary是非线程安全的,多线程时对其使用foreach可能会引起错误,多线程时推荐使用非泛型的Hashtable(或者自己lock..)。
[整理自网络]

: https://blog.darkmi.com/2013/08/07/864.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.