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 (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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With