我想创建指定范型类型参数的 Func 类型,类似于以下代码,但只使用一条语句。
当然,我可以创建辅助数组:
Type create_type(Type[] types)
{
return typeof(Func<>).MakeGenericType(types); // error if types.Length != 1
return typeof(Func<,>).MakeGenericType(types); // error if types.Length != 2
return typeof(Func<,,>).MakeGenericType(types); // error if types.Length != 3
return typeof(Func<,,,>).MakeGenericType(types); // error if types.Length != 4
// ....
}
当然,我可以创建辅助数组:
var func_types = new Type[] { typeof(Func<>), typeof(Func<,>) , //...}
但是这个解决方案对我来说看起来太丑陋了。
注意:类型数组可能很长(最多达到15个),我想找到一个优雅的解决方案。不幸的是,我正在从另一种语言编写的元数据中创建这样的类型。