vendredi 8 septembre 2023

Replace Generic Types In `System.Type[]` With Types

Say one has a generic definition MethodInfo object, that is, a MethodInfo object such that methodInfo.IsGenericMethodDefinition == true:

MethodInfo methodInfo = somethingCool;

Say also that they also have a list of generic arguments:

Type[] genericArguments = somethingElseAlsoCool;

I can get the types of the parameters of the method with:

Type[] types = (
    from ParameterInfo parameter
    in methodInfo.GetParameters()
    select parameter.ParameterType
    ).ToArray();

Now, I can fill in the generic arguments to methodInfo with methodInfo.MakeGenericMethod:

MethodInfo invokableMethodInfo = methodInfo.MakeGenericMethod(genericArguments);

However, what about the array of Types? I can just prematurely increment though the types as such:

for (int i = 0; i < types.Length; i++)
    types[i] = types[i].MakeGenericType(genericArguments);

But this wouldn't make sense. Consider the following method:

void MyGenericMethod<TOne, TTwo, TThree>(IDictionary<TOne, TThree> Dictionary);

If I did the previously mentioned algorithm, then the types would map incorrectly:

TOne   => TKey   //Fine, but only by coincidence.
TTwo   => TValue //Incorrect. TValue should be TThree, not TTwo.
TThree => ?      //What is this?

I'm stumped. How can I define the undefined generics in my array of types?

Any help would be greatly appreciated!





Aucun commentaire:

Enregistrer un commentaire