Add type parameter constraint to prevent abstract classes

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

    public class ZooPen where T : Animal
    {
        public ZooPen()
        {
            if (typeof(T).IsAbstract)
                throw new ArgumentException(typeof(T).Name + " must be non abstract class");
        }
    }
    

提交回复
热议问题