Making Generics with many types
I have a chunk of code where sometimes I need to create a new generic type, but with an unknown number of generic parameters. For example:
public object MakeGenericAction(Type[] types)
{
return typeof(Action<>).MakeGenericType(paramTypes);
}
The problem is that if I have more than one Type in my array, then the program will crash. In the short term I have come up with something like this as a stop-gap.
public object MakeGenericAction(Type[] types)
{
if 开发者_如何学JAVA(types.Length == 1)
{
return typeof(Action<>).MakeGenericType(paramTypes);
}
else if (types.Length ==2)
{
return typeof(Action<,>).MakeGenericType(paramTypes);
}
..... And so on....
}
This does work, and is easy enough to cover my scenarios, but it seems really hacky. Is there a better way to handle this?
In that case, yes:
Type actionType = Expression.GetActionType(types);
The problem here though is that you will probably be using DynamicInvoke which is slow.
An Action<object[]>
then access by index may outperform an Action<...>
invoked with DynamicInvoke
Assembly asm = typeof(Action<>).Assembly;
Dictionary<int, Type> actions = new Dictionary<int, Type>;
foreach (Type action in asm.GetTypes())
if (action.Name == "Action" && action.IsGenericType)
actions.Add(action.GetGenericArguments().Lenght, action)
then you can use the actions
dictionary to quickly find the right type:
public Type MakeGenericAction(Type[] types)
{
return actions[types.Lenght].MakeGenericType(paramTypes);
}
精彩评论