swollaws
漂泊中体会不到生活的味道,那是因为吃不到老妈烧的饭。
      .NET Framework类库在System.Collections.Generic命名空间中包含几个新的泛型集合类。应尽可能地使用这些类来代替普通的类,如ystem.Collections 命名空间中的ArrayList,HashTable等。
非泛型类(System.Collections) 对应的泛型类(System.Collections.Generic)
ArrayList List
Hashtable Dictionary
Queue Queue
Stack Stack
SortedList SortedList

         泛型优点:

               1、性能:主要是针对装箱和拆箱操作。

            2、类型安全:如 

                  ArrayList list = new ArrayList();

            list.Add(15);

            list.Add("Text");

            list.Add(new Person());使用下面的foreach语句遍历,就会出现一个运行异常。

            foreach (int i in list)

            {

                Console.Write(i);

            }

 

 

            3、二进制代码的重用:泛型类可以定义一次,用许多不同的类型实例化。

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

            list.Add(1);

            List<string> stringList = new List<string>();

            list.Add("string");

            List<Person> personList = new List<Person>();

               personList.Add(new Person());

 

            4、代码的扩展

         简单实例:

using System;

using System.Collections.Generic;

using System.Text;

namespace Text

{

    class Program

    {

        static void Main(string[] args)

        {

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

            list.Add("泛型集合元素1");

            list.Add("泛型集合元素2");

            foreach (string text in list)

                Console.WriteLine(text);

            Console.WriteLine("");

 

            Dictionary<string, string> dct = new Dictionary<string, string>();

            dct.Add("键1", "值1");

            dct.Add("键2", "值2");

            foreach (KeyValuePair<string, string> kvp in dct)

                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);

            Console.WriteLine("");

 

            Queue<string> que = new Queue<string>();

            que.Enqueue("这是队列元素值1");

            que.Enqueue("这是队列元素值2");

            foreach (string text in que)

                Console.WriteLine(text);

            Console.WriteLine("");

 

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

            stack.Push("这是堆栈元素1");

            stack.Push("这是堆栈元素2");

            foreach (string text in stack)

                Console.WriteLine(text);

            Console.WriteLine("");

 

            SortedList<string, string> sortedList = new SortedList<string, string>();

            sortedList.Add("key1", "value1");

            sortedList.Add("key2", "value2");

            foreach (KeyValuePair<string, string> kvp in sortedList)

                Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);

 

            Console.ReadLine();

        }

    }

}

 

posted on 2009-05-11 18:11  swollaw  阅读(283)  评论(0编辑  收藏  举报