为继承父类并实现接口的泛型类定义T的类型约束
为泛型抽象类AbstractComponent添加类型约束的方法
要给AbstractComponent<T>的类型参数T添加where T : class, new()约束,直接在类定义的末尾追加where子句即可,具体修改后的代码如下:
abstract class AbstractComponent<T> : Parent, IComponentType, IRelationship where T : class, new() {} class ChildComponent : AbstractComponent<CarComponent> {}
关键说明
class约束:要求T必须是引用类型(涵盖类、接口、委托或数组类型)new()约束:要求T必须具备公共的无参数构造函数,因此你传入的CarComponent必须满足这个条件,否则会触发编译错误
内容的提问来源于stack exchange,提问作者the-petrolhead
相关产品推荐
相关产品推荐

