天天看點

泛型--完全手冊C#2.0

非泛型類(System.Collections)

對應的泛型類(System.Collections.Generic)

ArrayList

List

Hashtable

Dictionary

Queue

Stack

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)

            //使用Stack<T>

            Console.WriteLine("Stack泛型集合類舉例");

            Stack<string> stack = new Stack<string>();

            stack.Push("這是堆棧元素1");

            stack.Push("這是堆棧元素2");

            foreach (string s in stack)

            //使用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.ReadLine();

        }

    }

}

部落格園大道至簡

<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>

轉載請注明:部落格園