2017-08-11 206 views
0

我想打电话给Invoke()但它总是抛出:无法调用invoke()

对象不匹配目标类型

我不知道以什么作为第一通参数 - 假设这是问题 - 我尝试了许多事情,但都没有运气。下面进入我的代码:

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

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

BaseRepository是:

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

City类是:

public class City : Entity 

而且Entity是一个抽象类:

public abstract class Entity 

作为第一个Invoke的参数,我尝试过使用City的实例 - 这应该是正确的情况 - Entity的实例以及其他我确信实际上无法正常工作的实例。

+1

你有'''''''''''''''''''''''''''''''''''' –

+0

具体而言,根据您的类定义实现IBaseRepository ' –

+0

的实例必须是新的BaseRepository (),因为“Invoke”的第一个参数被记录为“调用方法或构造函数的对象” – dlatikay

回答

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

是的,它的工作原理。我的最终解决方案唯一的区别是'repo'部分,我必须使用我的依赖注入器来解析*,但我设法使它工作!您的提示帮助,非常感谢。 – DontVoteMeDown

+0

有人真的对这个问题很生气,并且是免费的downvoting .. – DontVoteMeDown

+0

你的更好的选择将是把另一个接口,不关心泛型类型参数,只是把它放在你的回购协议...然后你不需要反思。 –