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

如何定义层级使InputManager<ClassA> is InputManager<IShooter>为true?

解决方案:利用泛型协变实现类型兼容性

你遇到的问题本质是C#泛型的不变性:默认情况下,泛型类的类型参数是不变的,即使ClassA实现了IShooter,InputManager<ClassA>和InputManager<IShooter>也属于完全独立的类型,不存在继承或兼容关系,因此is判断返回false。

要实现目标类型兼容性,需要借助C#的泛型协变特性——注意:只有泛型接口和委托支持协变,泛型类本身不支持,因此需要调整层级定义:

步骤1:定义协变泛型接口

创建一个标记了out关键字的协变接口,out表示类型参数T仅用于输出位置(比如方法返回值、只读属性):

public interface IInputManager<out T> where T : IShooter
{
    // 示例协变成员:T只能作为返回值
    T GetCurrentShooter();
}

步骤2:让抽象类实现协变接口

修改原有的InputManager<T>抽象类,让它实现上面的协变接口:

public abstract class InputManager<T> : IInputManager<T> where T : IShooter
{
    public abstract T GetCurrentShooter();
    
    // 原有的部分实现代码...
}

验证效果

此时执行以下判断会返回true:

var inputMgr = new ConcreteInputManager<ClassA>(); // 假设ConcreteInputManager是InputManager<ClassA>的具体实现
bool result = inputMgr is IInputManager<IShooter>; // result为true

关键说明

  • 如果你坚持要直接判断InputManager<ClassA> is InputManager<IShooter>,这是做不到的——因为C#泛型类不支持协变/逆变,只能通过协变接口间接实现类型兼容。
  • 协变接口的限制:类型参数T不能作为方法的输入参数(比如方法参数、可写属性的setter),否则编译器会报错。

内容的提问来源于stack exchange,提问作者JLagana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:20:00