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个),我想找到优雅的解决方案.不幸的是,我正在用另一种语言编写的元数据创建这种类型
Func和Action的Expression类中有静态方法,它们可以满足您的需求
Expression.GetFuncType(Type[] types)
Expression.GetActionType(Type[] types)
Run Code Online (Sandbox Code Playgroud)
更多信息: