木子屋 Dnawo's BLOG

ArrayList,List,Hashtable,Dictionary的应用

👤 dnawo 📅 2008-07-04 👁 4556 👍 0 💬 0 🔄 海蓝的天空
ArrayList的应用(System.Collections)

ArrayList list = new ArrayList();

list.Add(new Student("aaa", 20));
list.Add(new Student("bbb", 21));
list.Add(new Student("ccc", 22));

for (int i = 0; i < list.Count; i++)
{
    Student stu = list[i] as Student;
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}
foreach (Object obj in list)
{
    Student stu = obj as Student;
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}

List<T>的应用(System.Collections.Generic)

List<Student> list = new List<Student>();

list.Add(new Student("aaa", 20));
list.Add(new Student("bbb", 21));
list.Add(new Student("ccc", 22));

for (int i = 0; i < list.Count; i++)
{
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", list[i].Name, list[i].Age));
}
foreach (Student stu in list)
{
    Console.WriteLine(string.Format("Name:{0}   Age:{1}", stu.Name, stu.Age));
}

Hashtable的应用(System.Collections)

Hashtable hs = new Hashtable();

hs.Add("aaa", 20);
hs.Add("bbb", 21);
hs.Add("ccc", 22);

foreach (DictionaryEntry de in hs)
{
    Console.WriteLine(string.Format("Key:{0}    Value:{1}",de.Key,de.Value));
}

Dictionary<TKey, TValue>的应用(System.Collections.Generic)

Dictionary<string, int> dict = new Dictionary<string, int>();

dict.Add("aaa", 20);
dict.Add("bbb", 21);
dict.Add("ccc", 22);

foreach (KeyValuePair<string, int> kvp in dict)
{
    Console.WriteLine(string.Format("Key:{0}    Value:{1}", kvp.Key, kvp.Value));
}

说明:如果存储的元素是Object类型时,List<T>和Dictionary<TKey, TValue>会优于ArrayList和HashTable,因为在存储或检索值类型时ArrayList和HashTable经常要进行装箱和拆箱。

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 ASP.NET2.0个性化用户配置之存储匿名/登录用户信息 下一篇 → 比较Select Case(VB.NET)和switch(C#)