vendredi 29 janvier 2021

Variable generic type count runtime reflection

Right now I have this code:

//some Method detection here..

var methodParams = method.GetParameters();
Type actionType = null;

switch(methodParams.Length)
{
    case 1:
        actionType = typeof(Action<>);
        break;

    case 2:
        actionType = typeof(Action<,>);
        break;

    case 3:
        actionType = typeof(Action<,,>);
        break;

    case 4:
        actionType = typeof(Action<,,,>);
        break;

    case 5:
        actionType = typeof(Action<,,,,>);
        break;
}

var actionGenericType = actionType.MakeGenericType(methodParams.Select(x => x.ParameterType).ToArray());

I don't like this switch statement but I haven't yet found a way to select the Action generic overload based on the number of parameters (or based on any runtime int).

Is there a more elegant way / oneliner to do something like this?

I don't want to use a dispatch table.





Aucun commentaire:

Enregistrer un commentaire