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

如何使用Activator为带泛型params参数的类型传入null数组完成实例化

问题根因

你遇到的MissingMethodException由两个问题共同导致:

  • 泛型类型使用错误:MyType<T>是开放泛型定义,不能直接用typeof(MyType)作为创建实例的类型,需要先指定泛型参数T构造出闭合的泛型类型
  • 参数类型不匹配:params T[]是C#语法糖,构造函数的第三个参数实际类型是T[],你传入的无类型null无法被运行时识别为T[]类型,导致构造函数签名匹配失败

解决方案

场景1:提前知道泛型参数T的类型

示例以T = int为例,可替换为你实际需要的类型:

// 1. 构造闭合泛型类型
Type closedGenericType = typeof(MyType<>).MakeGenericType(typeof(int));
// 2. 显式传入T[]类型的null,匹配构造函数签名
var args = new object[] { 1, "foo", (int[])null };
// 3. 创建实例,注意BindingFlags要和构造函数实际访问修饰符匹配
var myType = Activator.CreateInstance(closedGenericType, BindingFlags.Instance | BindingFlags.Public, null, args, null);

场景2:泛型参数T是动态获取的

// 动态获取T的实际类型,这里以string为例
Type tType = typeof(string);
// 构造对应的T[]类型
Type arrayType = tType.MakeArrayType();
// 生成对应T[]类型的null值
object typedNull = Convert.ChangeType(null, arrayType);

object[] args = new object[] { 1, "foo", typedNull };
Type closedGenericType = typeof(MyType<>).MakeGenericType(tType);
var myType = Activator.CreateInstance(closedGenericType, BindingFlags.Instance | BindingFlags.Public, null, args, null);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:18:00