---------------------- Windows Phone 7手機開發、.Net培訓、期待與您交流! ----------------------
泛型:通過參數化類型來實現在同一份代碼上操作多種數據類型。利用“參數化類型”將類型抽象化,從而實現靈活的復用。
例子代碼:
class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? int obj = 2;
??????????? Test<int> test = new Test<int>(obj);
??????????? Console.WriteLine("int:" + test.obj);
??????????? string obj2 = "hello world";
??????????? Test<string> test1 = new Test<string>(obj2);
??????????? Console.WriteLine("String:" + test1.obj);
??????????? Console.Read();
??????? }
??? }
?
??? class Test<T>
??? {
??????? public T obj;
??????? public Test(T obj)
??????? {
??????????? this.obj = obj;
??????? }
}
??? 輸出結果是:
??? int:2
String:hello world
?
程序分析:
? Test是一個泛型類。T是要實例化的范型類型。如果T被實例化為int型,那么成員變量obj就是int型的,如果T被實例化為string型,那么obj就是string類型的。
? 根據不同的類型,上面的程序顯示出不同的值。
---------------------- Windows Phone 7手機開發、.Net培訓、期待與您交流! ----------------------