我想用指定的泛型类型参数创建 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 个),我想找到优雅的解决方案。不幸的是,我正在从元数据创建这种类型,用另一种语言编写
用于 Func 和 Action 的 Expression 类中有静态方法可以完全满足您的要求
Expression.GetFuncType(Type[] types)
Expression.GetActionType(Type[] types)
更多信息在这里:
GetFuncType
GetActionType
我是一名优秀的程序员,十分优秀!