Add type parameter constraint to prevent abstract classes

前端 未结 3 1218
囚心锁ツ
囚心锁ツ 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:17

    You can add the new() constraint, which will require that the class not be abstract and have a default constructor.

    0 讨论(0)
  • 2021-02-20 04:24
    public class ZooPen<T> where T : Animal
    {
        public ZooPen()
        {
            if (typeof(T).IsAbstract)
                throw new ArgumentException(typeof(T).Name + " must be non abstract class");
        }
    }
    
    0 讨论(0)
  • 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<T> : Animal where T : Animal<T>
    {
        public Animal(string name) : base(name) { }
    }
    
    class Penguin : Animal<Penguin>
    {
        public Penguin() : base("Penguin") { }
    }
    
    class Chimpanzee : Animal<Chimpanzee>
    {
        public Chimpanzee() : base("Chimpanzee") { }
    }
    
    class ZooPen<T> where T : Animal<T>
    {
    }
    
    class Example
    {
        void Usage()
        {
            var penguins = new ZooPen<Penguin>();
            var chimps = new ZooPen<Chimpanzee>();
            //this line will not compile
            //var animals = new ZooPen<Animal>();
        }
    }
    

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

    0 讨论(0)
提交回复
热议问题