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

C#泛型重写时使用二维数组报错问题咨询

C#泛型方法重写:二维数组作为参数的报错解决

问题场景

定义了抽象泛型导出方法:

public abstract Output Export<Input, Output>(Input input);

尝试用二维数组作为泛型参数重写时,以下写法会触发语法报错:

public override Object2[][] Export<Object1[][], Object2[][]>(Object1[][] input) {
    throw new System.NotImplementedException();
}

报错原因

C#语法规则不允许在泛型类型参数的声明中直接使用数组类型(比如Object1[][]这种带方括号的写法不能作为泛型参数占位符)。泛型参数本身应当是基础类型,数组的维度修饰符需要放在方法的参数和返回值类型上,而非泛型参数的定义里。

正确写法

通用二维数组重写

如果要支持任意类型的二维数组输入输出,泛型参数声明为基础类型,在参数和返回值中指定数组维度:

public override Object2[][] Export<Object1, Object2>(Object1[][] input)
{
    // 实现导出逻辑
    throw new System.NotImplementedException();
}

如果需要约束Object1或Object2的类型,可以添加where约束,例如:

public override Object2[][] Export<Object1, Object2>(Object1[][] input)
    where Object1 : MyBaseClass
    where Object2 : MyBaseClass
{
    throw new System.NotImplementedException();
}

特定类型二维数组重写

如果只需要针对某一特定类型的二维数组实现重写(比如int[][]输入,string[][]输出),可以直接指定泛型参数的具体类型:

public override string[][] Export<int, string>(int[][] input)
{
    // 针对int二维数组转string二维数组的实现
    throw new System.NotImplementedException();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:42:47