vendredi 16 novembre 2018

Invoke method on generic base class using Reflection via derived type

I'm trying to invoke a method on a base class via reflection, but GetMethods(...) does not find the method.

My base class looks like this:

public abstract class MyBase<S, T> where S : class, new()
                                   where T : ILocalizableTitle
{
    public IEnumerable<T> For(string systemLangCode)
    {
        // ...
    }

    public IEnumerable<T> For(Person person)
    {
        // ...
    }

    public IEnumerable<T> For(CultureInfo cultureInfo, long tenantId)
    {
        // ...
    }

    public static IEnumerable<Type> GetAllMyTypes()
    {
        var thisType = new StackFrame().GetMethod().DeclaringType;

        return (
                   from t in Assembly.GetExecutingAssembly().GetTypes()
                   where t.IsClass
                         && t.Namespace == thisType?.Namespace
                         && t.BaseType?.Name == thisType?.Name
                   select t).ToList();
    }

    public void Reset()
    {
        // ...
    }
}

I'm obtaining a derived type via Reflection...

var myDerivedType = MyBase<object, ILocalizableTitle>.GetAllMyTypes().FirstOrDefault(t => t.Name == forTypeByName);

From myDerivedType I expected to see the Reset method by using the following:

var publicMethods = myDerivedType.GetMethods(BindingFlags.Public | BindingFlags.FlattenHierarchy)

But publicMethods is empty.

How can I get and invoke the Reset method if I have an instance of a derived type?





Aucun commentaire:

Enregistrer un commentaire