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

如何在C#泛型定义中正确使用where约束子句?

C#泛型约束错误修正方案

原代码

public interface ITypeInterface { }

public interface IType1Things<T> where T : ITypeInterface
{
}

public interface IType2Things<T> where T : ITypeInterface
{
}

public interface ICommonInterface<T1, T2>
    where T1 : ITypeInterface
    where T2 : ITypeInterface
    , IType1Things<T1>
    , IType2Things<T2>
{
}

public class Implementation<T1, T2>
    where T1 : ITypeInterface
    where T2 : ITypeInterface
    , ICommonInterface<T1, T2>
{
}

编译器报错

无法将类型“T2”用作泛型类型或方法“ICommonInterface<T1, T2>”中的类型参数“T2”。不存在从“T2”到“ClassLibrary1.IType1Things”的装箱转换或类型参数转换。

错误原因

问题出在ICommonInterface<T1,T2>的泛型约束中,你给T2额外添加了IType1Things<T1>的约束,这导致Implementation类中T2在实现ICommonInterface<T1,T2>时,必须满足T2实现IType1Things<T1>,而这并不是你的需求。

正确写法

如果你仅需要T1和T2都实现ITypeInterface,只需移除ICommonInterface<T1,T2>中T2的多余约束即可:

public interface ITypeInterface { }

public interface IType1Things<T> where T : ITypeInterface
{
}

public interface IType2Things<T> where T : ITypeInterface
{
}

public interface ICommonInterface<T1, T2>
    where T1 : ITypeInterface
    where T2 : ITypeInterface
{
}

public class Implementation<T1, T2>
    where T1 : ITypeInterface
    where T2 : ITypeInterface
    , ICommonInterface<T1, T2>
{
}

如果你的ICommonInterface原本需要T2实现IType2Things<T2>(这是和T2自身相关的约束),也可以保留该约束,不会引发冲突:

public interface ICommonInterface<T1, T2>
    where T1 : ITypeInterface
    where T2 : ITypeInterface, IType2Things<T2>
{
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:57:08