《.NET 性能優(yōu)化》—第五章 泛型

泛型是.NET Framework2.0新增的一個(gè)特性,在命名空間System.Collections.Generic,包含了幾個(gè)新的基于泛型的集合類。

泛型解決了類型安全和裝箱問(wèn)題。

  • 類型安全: 在編譯時(shí)驗(yàn)證對(duì)于泛型數(shù)據(jù)類型的操作,明確禁止那些可能在運(yùn)行時(shí)出錯(cuò)的行為。
  • 在參數(shù)為object引用時(shí),避免對(duì)值類型進(jìn)行裝箱。
    例如:
ArrayList emp = new ArrayList(7);
emp.add("hello");
emp.add("world");
emp.add(32);

上面的代碼不僅添加了不同類型的數(shù)據(jù)作為一個(gè)列表。然而,如果使用泛型List<T>則不會(huì)出現(xiàn)類似的情況。泛型集合是類型安全的,不允許存儲(chǔ)不匹配的元素,并且不會(huì)對(duì)值類型裝箱。
例如,當(dāng)你定義了一個(gè)List<string>, 該列表中便約束了你的數(shù)據(jù)類型,如下顯示:



泛型約束


參考: C#泛型約束 - 雨文木可 - 博客園
泛型的使用有系統(tǒng)自定義的一些泛型類型,泛型方法,泛型委托等,也可以自定義泛型的使用。

Demo

以下做了一個(gè)小Demo,分別是泛型類下使用泛型方法和非泛型方法, 非泛型類下使用非泛型方法和泛型方法。
Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericTest
{
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass<int> class1 = new GenericClass<int>();
            class1.Say();
            class1.Say(8);

            GenericClass2 class2 = new GenericClass2();
            class2.Say();
            class2.Say<int>(8);

            Console.ReadLine();

        }
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericTest
{
    public class GenericClass<T>
    {
        public void Say()
        {
            // do nothing
        }

        public void Say(T t1)
        {
            Console.WriteLine($"{t1}");
        }
    }

    public class GenericClass2
    {
        public void Say()
        {
            // do nothing
        }

        public void Say<T>(T t1)
        {
            Console.WriteLine($"{t1}");
        }
    }
}

Result:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容