非泛型类(System.Collections) 对应的泛型类(System.Collections.Generic)
ArrayList List
Hashtable Dictionary
Queue Queue
Stack Stack
SortedList SortedList

使用泛型的建议:

1.如果需要对多种类型进行相同的操作处理,则应该使用泛型。

2。如果需要处理值类型,则使用泛型可以避免装箱拆箱带来的性能开销。

3.使用泛型可以在应用程序编译时发现类型错误,增强程序的健壮性。

4.减少不必要的重复编码,使代码结构更加清晰。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //
使用List<T>替换ArrayList
            List<string> ls = new List<string>();
            ls.Add("
泛型集合元素1");
            ls.Add("
泛型集合元素2");
            ls.Add("
泛型集合元素3");
            foreach (string s in ls)
                Console.WriteLine(s);

        //使用Dictionary<Tkey,Tvalue>
            Console.WriteLine("Dictinary
泛型集合类举例");
            Dictionary<string, string> dct = new Dictionary<string, string>();
            dct.Add("
1", "1");
            dct.Add("
2", "2");
            dct.Add("
3", "3");
            foreach (KeyValuePair<string, string> kvp in dct)
                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
           
            //
使用Queue<T>
            Console.WriteLine("Queue
泛型集合类型:");
            Queue<string> que = new Queue<string>();
            que.Enqueue("
这是队列元素值1");
            que.Enqueue("
这是队列元素值2");
            foreach (string s in que)
                Console.WriteLine(s);

            //使用Stack<T>
            Console.WriteLine("Stack
泛型集合类举例");
            Stack<string> stack = new Stack<string>();
            stack.Push("
这是堆栈元素1");
            stack.Push("
这是堆栈元素2");
            foreach (string s in stack)
                Console.WriteLine(s);

            //使用SortedList<Tkey,Tvalue>
            Console.WriteLine("SortedList
泛型集合举例");
            SortedList<string, string> sl = new SortedList<string, string>();
            sl.Add("key1", "value1");
            sl.Add("key2", "value2");
            sl.Add("key3", "value3");
            sl.Add("key4", "value4");
            foreach (KeyValuePair<string, string> kvp in sl)
                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);

            Console.ReadLine();
        }
       
    }
}

 

posted on 2008-08-21 17:29  梅桦  阅读(268)  评论(0编辑  收藏  举报