C# 泛型(Generic)

2022-09-20 15:13 更新

泛型(Generic) 允許您延遲編寫類或方法中的編程元素的數(shù)據(jù)類型的規(guī)范,直到實(shí)際在程序中使用它的時(shí)候。換句話說,泛型允許您編寫一個(gè)可以與任何數(shù)據(jù)類型一起工作的類或方法。


實(shí)例

您可以通過數(shù)據(jù)類型的替代參數(shù)編寫類或方法的規(guī)范。當(dāng)編譯器遇到類的構(gòu)造函數(shù)或方法的函數(shù)調(diào)用時(shí),它會(huì)生成代碼來處理指定的數(shù)據(jù)類型。下面這個(gè)簡(jiǎn)單的實(shí)例將有助于您理解這個(gè)概念:

using System;
using System.Collections.Generic;

namespace GenericApplication{
    public class MyGenericArray<T>{
        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){
            // 聲明一個(gè)整型數(shù)組
            MyGenericArray<int> intArray = new MyGenericArray<int>(5);
            // 設(shè)置值
            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();             // 聲明一個(gè)字符數(shù)組
            MyGenericArray<char> charArray = new MyGenericArray<char>(5);
            // 設(shè)置值
            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();
        }
    }
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

0 5 10 15 20
a b c d e

泛型(Generic)的特性

使用泛型是一種增強(qiáng)程序功能的技術(shù),具體表現(xiàn)在以下幾個(gè)方面:

  • 它有助于您最大限度地重用代碼、保護(hù)類型的安全以及提高性能。
  • 您可以創(chuàng)建泛型集合類。.NET 框架類庫在 System.Collections.Generic 命名空間中包含了一些新的泛型集合類。您可以使用這些泛型集合類來替代 System.Collections 中的集合類。
  • 您可以創(chuàng)建自己的泛型接口、泛型類、泛型方法、泛型事件和泛型委托。
  • 您可以對(duì)泛型類進(jìn)行約束以訪問特定數(shù)據(jù)類型的方法。
  • 關(guān)于泛型數(shù)據(jù)類型中使用的類型的信息可在運(yùn)行時(shí)通過使用反射獲取。

泛型(Generic)方法

在上面的實(shí)例中,我們已經(jīng)使用了泛型類,我們可以通過類型參數(shù)聲明泛型方法。下面的程序說明了這個(gè)概念:

using System;
using System.Collections.Generic;

namespace GenericMethodAppl{
    class Program{
        static void Swap<T>(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);

            // 調(diào)用 swap
            Swap<int>(ref a, ref b);
            Swap<char>(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();
        }
    }
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

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

泛型(Generic)委托

您可以通過類型參數(shù)定義泛型委托。例如:

delegate T NumberChanger<T>(T n);

下面的實(shí)例演示了委托的使用:

using System;
using System.Collections.Generic;

delegate T NumberChanger<T>(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){
            // 創(chuàng)建委托實(shí)例
            NumberChanger<int> nc1 = new NumberChanger<int>(AddNum);
            NumberChanger<int> nc2 = new NumberChanger<int>(MultNum);
            // 使用委托對(duì)象調(diào)用方法
            nc1(25);
            Console.WriteLine("Value of Num: {0}", getNum());
            nc2(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

Value of Num: 35
Value of Num: 175


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)