[C#] 泛型的意義 (Generics)

  • 55592
  • 0
  • 2011-01-25

[C#] 泛型的意義

Interduction

對於邏輯處理相同而僅資料型態不同的兩個程式可以使用泛型類別來處理。

透過泛型的宣告,變數型態在類別使用時再自動調整。

.net 已經有許多泛型的 Library ,如 : System.Collections.Generic 命名空間,還有許多資訊連結如下。

 

Example

在定義泛型類別時不指定某些變數的具體類型,而是用一個類型參數代替,在使用這個類別時,這個類型的參數會由

一個具體的類型所代替,比較下面兩個例子。

sample1:


	namespace TestGenerics {
    class Program {
        static void Main(string[] args) {
            Record<string> score1 = new Record<string>("Alex", "A");           
            Console.WriteLine("Alex " + score1.Getgrade());

            Console.ReadKey();
        }
    }

    public class Record<T> {
        private string _name;
        private T _grade;

        public Record(string name, T grade) {
            this._name = name;
            this._grade = grade;
        }

        public T Getgrade() {
            return this._grade;
        }
    }
}

sample2:


	namespace TestGenerics {
    class Program {
        static void Main(string[] args) {
            Record<int> score1 = new Record<int>("Alex", 80);           
            Console.WriteLine("Alex " + score1.Getgrade());

            Console.ReadKey();
        }
    }

    public class Record<T> {
        private string _name;
        private T _grade;

        public Record(string name, T grade) {
            this._name = name;
            this._grade = grade;
        }

        public T Getgrade() {
            return this._grade;
        }
    }
}

 

sample3:

泛型類別可以支援一個以上的泛型變數,兩者型態一致。


	public class Record<T> {
        private string _name;
        private T _math;
        private T _phy;

        public Record(string name,T math,T phy{
            this._name = name;
            this._math = math;
            this._phy = phy;
        }

        public T GetMath(){
            return this._math
        }

        public T GetPhy(){
            return this._phy;
        }
    }

 

sample4:

兩者型態也可不一致,就要宣告兩個型態的關鍵字。


	public class Record<S, T>{
    private string _name;
    private T _math;  
    private S _phy;
    
    public Record(String name, S phy, T math) {  
        this._name = name;    
        this._math = math;   
        this._phy = phy;  
    } 

    public T GetMath() {
        return this._math;
    }

    public S GetPhy()
    {
        return this._phy;
    }
}

 

延伸閱讀:

Huan-Lin 學習筆記 中有提到  [C#] 泛型 = 樣板 ,可以參考看看。

 

後記:

補充1:

若要在 Method 達到泛型的效果,又該如何做呢?參考以下:

class Program {       
        static void Main(string[] args) {
            Console.WriteLine(Show<string>("Hello!"));
            Console.ReadKey();
        }

        static T Show<T>(T t) {
            T Result = t;
            return Result;
        }
    }

輸出結果:

 

class Program {       
        static void Main(string[] args) {
            Console.WriteLine(Show<int>(9999));
            Console.ReadKey();
        }

        static T Show<T>(T t) {
            T Result = t;
            return Result;
        }
    }

輸出結果:

 

檔案下載:TestGenerics.rar

三小俠  小弟獻醜,歡迎指教