如何使用指定的泛型类型创建func类型?

LmT*_*oon 1 c# generics reflection

我想用指定的泛型类型参数创建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
// .... 
}
Run Code Online (Sandbox Code Playgroud)

当然,我可以创建辅助阵列:

var func_types = new Type[] { typeof(Func<>), typeof(Func<,>) , //...}
Run Code Online (Sandbox Code Playgroud)

但这个解决方案对我来说似乎太难看了

注意:类型数组可以很长(最多15个),我想找到优雅的解决方案.不幸的是,我正在用另一种语言编写的元数据创建这种类型

CSh*_*pie 8

Func和Action的Expression类中有静态方法,它们可以满足您的需求

Expression.GetFuncType(Type[] types)

Expression.GetActionType(Type[] types)
Run Code Online (Sandbox Code Playgroud)

更多信息:

GetFuncType

GetActionType

  • 然后我收回上面关于所需的丑陋代码的所有评论:)结果只是一个问题是谁将要编写那些丑陋或错综复杂的代码 - https://referencesource.microsoft.com/#System.Core/Microsoft/脚本/编译器/ DelegateHelpers.Generated.cs,227 (2认同)