7.6泛型编程

时间:2022-01-04 19:25:50

定义: 通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用.


 

例:

 class Test<T>
    {
        public T obj;
        public Test(T obj)
        {
            this.obj = obj;
        }
   }

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();
        }
    }