mardi 7 août 2018

Invoking a non-generic method which is declared in a base generic class throws exception with message

Invoking a non-generic method which is declared in a base generic class throws exception with this message:

"Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true"

I have decent experience on reflection but the recent change I made in my code caused a very rare case which I can't figure out.

I researched the web for a long long time and I have tried many possible/suggested solutions but I couldn't find the solution for my rare case.

All of the examples on the web are providing solutions for generic methods but in my case, the method I try to invoke is NOT generic. The class which contains the method is NOT generic. The class inherits a base class and only this base class IS generic.

Can anyone please give me any idea about correctly invoking a non-generic method which belongs to a non-generic class which inherits from a generic base class?

I'll try to isolate the problem and provide sample code which's highly trimmed so you can see what I mean.

Sidenote: Please don't suggest me to change my approach. I have to do this via Reflection and this class structure can't change. I'm trying to find a solution to this very specific case. Please don't be the person who don't know the specific answer but tries to convince me to change my approach.

// Execution starts here in some code piece.
// We don't know the type of Instance.
// It can either be SubClassA or SubClassB.
{
    // This finds the method correctly. It doesn't return null.
    MethodInfo ValidationMethod = Instance.GetType().GetMethod("Validate", BindingFlags.NonPublic | BindingFlags.Instance);

    // This throws the exception with the message shown above.
    ValidationMethod.Invoke(Instance, null);
}

public class SubClassA : BaseClass<EventArgs>
{
}

public class SubClassB : BaseClass<CancelEventArgs>
{
}

public abstract class BaseClass<T>
{
    void Validate()
    {
        Debug.Log("Validating");
    }
}





Aucun commentaire:

Enregistrer un commentaire