A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 柏森仁 中级黑马   /  2012-8-10 14:47  /  2029 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:

非泛型&弱类型的Collections(ArrayList,Queue,Stack):
使用object:
[size=1em]?

ArrayList al = new ArrayList();
al.Add("hello");
al.Add(1);
[color=#00ff !important]foreach(object obj in al)
{
    Console.WriteLine(obj.ToString());
}

如果确定ArrayList中的类型的话,也可以用这个类型代理,会自动强转,但若转换不成功,抛出InvalidCastException
[size=1em]?

ArrayList al = new ArrayList();
al.Add("hello");
al.Add("world");
[color=#00ff !important]foreach(string s in al)
{
    Console.WriteLine(s);
}

强类型的Collections(StringCollectionBitArray),可分别使用string和bool而无需强转。
非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):
使用DictionaryEntry:
[size=1em]?

Hashtable ht = new Hashtable();
ht.Add(1, "Hello");
ht.Add(2, "World");
[color=#00ff !important]foreach (DictionaryEntry de in ht)
{
    Console.WriteLine(de.Value);
}

特殊的Dictionary(NameValueCollection):
不能直接对NameValueCollection进行foreach遍历,需要两级:
[size=1em]?

NameValueCollection nvc = new NameValueCollection();
nvc.Add("a", "Hello");
nvc.Add("a", "World");
nvc.Add("b", "!");
[color=#00ff !important]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>:
[size=1em]?

Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "Hello");
dic.Add(2, "World");
[color=#00ff !important]foreach(KeyValuePair<int,string> pair in dic)
{
    Console.WriteLine(pair.Value);
}

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

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

1 个回复

倒序浏览
值得学习!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马