天天看点

泛型--完全手册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>

转载请注明:博客园