Search code examples
c#reflectionsystem.reflection

Can't call Invoke()


I'm trying to call Invoke() but it always throws:

Object does not match target type

I'm not sure what to pass as first parameter - presuming that this is the issue - and I have tried many things with no luck. Below goes my code:

var method = typeof(IBaseRepository<>).MakeGenericType(typeof(Domain.Model.Basic.City))
                 .GetMethod("Get", BindingFlags.Instance | BindingFlags.Public);

var entityData = method.Invoke(??, new[] { (object)id });

The BaseRepository is:

public class BaseRepository<T> : IBaseRepository<T>
{
    public virtual T Get(object id) { }
}

City class is:

public class City : Entity

And Entity is an abstract class:

public abstract class Entity

As first Invoke's parameter I have tried using an instance of City - which should be the right case - and instance of Entity and other things I was sure would not work actually.


Solution

  • //you are missing this part  (FYI, this won't work if BaseRepo<T> is abstract)
    var repoType = typeof(BaseRepository<>).MakeGenericType(typeof(City));
    var repo = repoType.GetConstructor(Type.EmptyTypes).Invoke(null);
    
    int id = 0; //whatever your id is...
    
    var method = typeof(IBaseRepository<>).MakeGenericType(typeof(City))
                    .GetMethod("Get", BindingFlags.Instance | BindingFlags.Public);
    var entityData = (Entity)method.Invoke(repo, new[] { (object)id }) ;