54. C# -- 泛型(Generic)

來源:互聯網
上載者:User

標籤:c#

 C# -- 泛型(Generic)


理論1:

泛型(Generic) 允許您延遲編寫類或方法中的編程元素的資料類型的規範,直到實際在程式中使用它的時候。

換句話說,泛型允許您編寫一個可以與任何資料類型一起工作的類或方法。

 您可以通過資料類型的替代參數編寫類或方法的規範。

當編譯器遇到類的建構函式或方法的函數調用時,它會產生代碼來處理指定的資料類型。

下面這個簡單的執行個體將有助於您理解這個概念:


執行個體1:

using System;using System.Collections.Generic;namespace GenericApplication{    public class MyGenericArray{        private T[] array;        public MyGenericArray(int size)        {            array = new T[size + 1];        }        public T getItem(int index)        {            return array[index];        }        public void setItem(int index, T value)        {            array[index] = value;        }    }               class Tester    {        static void Main(string[] args)        {            // 聲明一個整型數組            MyGenericArrayintArray = new MyGenericArray(5);            // 設定值            for (int c = 0; c < 5; c++)            {                intArray.setItem(c, c*5);            }            // 擷取值            for (int c = 0; c < 5; c++)            {                Console.Write(intArray.getItem(c) + " ");            }            Console.WriteLine();            // 聲明一個字元數組            MyGenericArraycharArray = new MyGenericArray(5);            // 設定值            for (int c = 0; c < 5; c++)            {                charArray.setItem(c, (char)(c+97));            }            // 擷取值            for (int c = 0; c < 5; c++)            {                Console.Write(charArray.getItem(c) + " ");            }            Console.WriteLine();            Console.ReadKey();        }    }}//當上面的代碼被編譯和執行時,它會產生下列結果://0 5 10 15 20//a b c d e

理論2:

泛型(Generic)的特性

使用泛型是一種增強程式功能的技術,具體表現在以下幾個方面:

  • 它有助於您最大限度地重用代碼、保護類型的安全以及提高效能。

  • 您可以建立泛型集合類。.NET 架構類庫在 System.Collections.Generic 命名空間中包含了一些新的泛型集合類。您可以使用這些泛型集合類來替代 System.Collections 中的集合類。

  • 您可以建立自己的泛型介面、泛型類、泛型方法、泛型事件和泛型委派。

  • 您可以對泛型類進行約束以訪問特定資料類型的方法。

  • 關於泛型資料類型中使用的類型的資訊可在運行時通過使用反射擷取。

泛型(Generic)方法

在上面的執行個體中,我們已經使用了泛型類,我們可以通過型別參數聲明泛型方法。下面的程式說明了這個概念:

執行個體2:

using System;using System.Collections.Generic;namespace GenericMethodAppl{    class Program    {        static void Swap(ref T lhs, ref T rhs)        {            T temp;            temp = lhs;            lhs = rhs;            rhs = temp;        }        static void Main(string[] args)        {            int a, b;            char c, d;            a = 10;            b = 20;            c = ‘I‘;            d = ‘V‘;            // 在交換之前顯示值            Console.WriteLine("Int values before calling swap:");            Console.WriteLine("a = {0}, b = {1}", a, b);            Console.WriteLine("Char values before calling swap:");            Console.WriteLine("c = {0}, d = {1}", c, d);            // 調用 swap            Swap(ref a, ref b);            Swap(ref c, ref d);            // 在交換之後顯示值            Console.WriteLine("Int values after calling swap:");            Console.WriteLine("a = {0}, b = {1}", a, b);            Console.WriteLine("Char values after calling swap:");            Console.WriteLine("c = {0}, d = {1}", c, d);            Console.ReadKey();        }    }}//當上面的代碼被編譯和執行時,它會產生下列結果://Int values before calling swap://a = 10, b = 20//Char values before calling swap://c = I, d = V//Int values after calling swap://a = 20, b = 10//Char values after calling swap://c = V, d = I

執行個體3:

泛型(Generic)委託

您可以通過型別參數定義泛型委派。例如:

delegate T NumberChanger(T n);

下面的執行個體示範了委託的使用:

using System;using System.Collections.Generic;delegate T NumberChanger(T n);namespace GenericDelegateAppl{    class TestDelegate    {        static int num = 10;        public static int AddNum(int p)        {            num += p;            return num;        }        public static int MultNum(int q)        {            num *= q;            return num;        }        public static int getNum()        {            return num;        }        static void Main(string[] args)        {            // 建立委託執行個體            NumberChangernc1 = new NumberChanger(AddNum);            NumberChangernc2 = new NumberChanger(MultNum);            // 使用委派物件調用方法            nc1(25);            Console.WriteLine("Value of Num: {0}", getNum());            nc2(5);            Console.WriteLine("Value of Num: {0}", getNum());            Console.ReadKey();        }    }}//當上面的代碼被編譯和執行時,它會產生下列結果://Value of Num: 35//Value of Num: 175


本文出自 “Ricky's Blog” 部落格,請務必保留此出處http://57388.blog.51cto.com/47388/1657396

54. C# -- 泛型(Generic)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.