.NET中爲什麼要使用泛型編程?

 .NET2.0中新添加了不少特性,其中重要的就是對泛型的支持。
那麼爲什麼要用到泛型,有什麼優勢?
.NET中對泛型的支持包含在System.Collections.Generic命名空間中,看以下一個簡單的例子:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Console_Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList al = new ArrayList();
            al.Add(5);
            al.Add(2);
            al.Add("hh");
            foreach (int i in al)
            {
                Console.WriteLine(i);
            }
        }
    }
}
此程序在運行過程當中會出現運行時錯誤:al.Add("hh");無法進行類型轉換。而我們經常需要的是在編譯期間發現錯誤,而不是把錯誤帶到運行期間,這樣,安全性得不到保證。
下面的程序:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Console_Generic
{
    class Program
    {
        static void Main(string[] args)
        {
           
            List<int> list = new List<int>();
            list.Add(5);
            list.Add(1);
            list.Add(5.0);
            foreach (int i in list)
            {
                Console.WriteLine(i);
            }
        }
    }
}
此程序在編譯期間不能通過,原因與上面的一致。但是在程序運行之前就可以發現錯誤。這正是我們所希望的。
在.NET中,所有的類型都單繼承子OBJECT,我們經常要對返回的OBJECT類型進行強制轉換,轉換成爲我們所希望的類型,例如:
 return (PetShop.IDAL.IProduct)Assembly.Load(path).CreateInstance(className);
該句在運行時動態加載程序集,同時創建了一個實例化的對象,但是最終強制轉化返回一個接口對象。
一般在強制轉換的過程當中是不安全的,因爲OBJECT對象可以隨便轉換爲你想要的任何類型,所以使用泛型有效避免了轉換過程中的不安全性。
其次,在將簡單的類型封裝位OBJECT類型進行傳遞時,伴隨這裝箱和拆箱的操作,而這兩個過程都會對性能造成很大的影響,但是使用泛型,沒有了這個繁瑣的過程,完成的是相同的功能,但是性能得到了提升。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章