C# 泛型 new()建構函式約束

iamzxf發表於2015-05-07

要求相應的類必須具備無引數的建構函式。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace newConstraint
{
    class class1 
    { 
        
    }
    class class2
    {
        public class2()
        {
            Console.WriteLine("class2");
        }
    }

    class class3
    {
        public class3()
        {
            Console.WriteLine("class 3, no parameter");
        }
        public class3(int n)
        {
            Console.WriteLine("class 3, with parameter");
        }
    }

    class GenClass<T> where T : new()
    {
        T field;
        public GenClass(){
            Console.WriteLine("====T====");
            field = new T();
        }
        
    }

    class Program
    {
        static void Main(string[] args)
        {
            GenClass<class1> c1 = new GenClass<class1>();
            GenClass<class2> c2 = new GenClass<class2>();
            GenClass<class3> c3 = new GenClass<class3>();
            Console.ReadLine();
        }
    }
}



相關文章