Making generics with many types

I have a piece of code where sometimes I need to create a new generic type, but with an unknown number of generic parameters. For instance:

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

The problem is that if there is more than one type in my array, the program will crash. In the short term, I came up with something like this as an intermediate 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.... } 

It really works and is easy enough to cover my scripts, but it seems really hacked. Is there a better way to handle this?

+6
source share
2 answers

In this case, yes:

 Type actionType = Expression.GetActionType(types); 

The problem here is that you are likely to use DynamicInvoke, which is slow.

An Action<object[]> , then index access can exceed Action<...> called using DynamicInvoke

+5
source
 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 type you need:

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

Source: https://habr.com/ru/post/889974/


All Articles