mercredi 22 mai 2019

Invoking generic method having generic type parameter using reflection

I want to invoke a generic method having two different generic type parameters. Below is what my method looks like:

public class ABC<T> : IABC<T> where T: class,new()
{
    public T Merge<T1>(T child, T parent, T1 rule){

    }
}

I want to invoke the Merge method from another method. Below is what I have tried to invoke it.

Type mergerType = GetType().GetGenericTypeDefinition();

Type constructed = mergerType.MakeGenericType(new[]
{
    childValue.GetType()
});

object mergerInstance = Activator.CreateInstance(constructed);

MethodInfo methodInfo = GetType().GetMethod("Merge");

MethodInfo method = methodInfo.MakeGenericMethod(ruleValue.GetType());

mergedObject = method.Invoke(mergerInstance, new[]
                {
                    childValue,
                    parentValue,
                    ruleValue
                });

While doing this I am getting a exception "object does not match target type invoke" after method.invoke(). I cannot change the class or method definition of ABC class or Merge method because many other classes are implementing the IABC interface. So can someone answer how can I invoke the Merge method.





Aucun commentaire:

Enregistrer un commentaire