You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为继承父类并实现接口的泛型类定义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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 11:42:37