Add type parameter constraint to prevent abstract classes

前端 未结 3 1237
囚心锁ツ
囚心锁ツ 2021-02-20 03:27

Is it possible to restrict a type parameter to concrete implementations of an abstract class, if those implementations don\'t have default constructors?

For example, if

3条回答
  •  野性不改
    2021-02-20 04:28

    Here is one way to accomplish what you're asking for.

    abstract class Animal
    {
        readonly string Name;
        Animal() { }
        public Animal(string name) { Name = name; }
    }
    
    abstract class Animal : Animal where T : Animal
    {
        public Animal(string name) : base(name) { }
    }
    
    class Penguin : Animal
    {
        public Penguin() : base("Penguin") { }
    }
    
    class Chimpanzee : Animal
    {
        public Chimpanzee() : base("Chimpanzee") { }
    }
    
    class ZooPen where T : Animal
    {
    }
    
    class Example
    {
        void Usage()
        {
            var penguins = new ZooPen();
            var chimps = new ZooPen();
            //this line will not compile
            //var animals = new ZooPen();
        }
    }
    

    Anyone maintaining this code will probably be a bit confused, but it does exactly what you want.

提交回复
热议问题