制作具有多种类型的generics

我有一大堆代码,有时我需要创建一个新的generics类型,但具有未知数量的generics参数。 例如:

public object MakeGenericAction(Type[] types) { return typeof(Action).MakeGenericType(paramTypes); } 

问题是,如果我的数组中有多个Type,那么程序将崩溃。 在短期内,我提出了类似这样的事情作为一个止损。

 public object MakeGenericAction(Type[] types) { if (types.Length == 1) { return typeof(Action).MakeGenericType(paramTypes); } else if (types.Length ==2) { return typeof(Action).MakeGenericType(paramTypes); } ..... And so on.... } 

这确实有效,并且很容易覆盖我的场景,但它似乎真的很hacky。 有没有更好的方法来处理这个?

在那种情况下,是的:

 Type actionType = Expression.GetActionType(types); 

这里的问题是你可能会使用速度很慢的DynamicInvoke。

然后,按索引访问的Action可能胜过使用DynamicInvoke调用的Action<...>

 Assembly asm = typeof(Action<>).Assembly; Dictionary actions = new Dictionary; foreach (Type action in asm.GetTypes()) if (action.Name == "Action" && action.IsGenericType) actions.Add(action.GetGenericArguments().Lenght, action) 

然后你可以使用actions字典快速找到正确的类型:

 public Type MakeGenericAction(Type[] types) { return actions[types.Lenght].MakeGenericType(paramTypes); }