简体   繁体   English

无法调用Invoke()

[英]Can't call Invoke()

I'm trying to call Invoke() but it always throws: 我正在尝试调用Invoke()但它总是抛出:

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: BaseRepository是:

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

City class is: City是:

public class City : Entity

And Entity is an abstract class: Entity是一个抽象类:

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. 作为第一个Invoke的参数,我尝试使用City实例-应该是正确的情况-以及Entity实例和其他我确定不会实际起作用的东西。

//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 }) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM