我试图给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 : EntityEntity是一个抽象类:
public abstract class Entity作为第一次调用的参数,我尝试使用City的一个实例--这应该是正确的情况--以及Entity的实例和其他我确信不起作用的东西。
发布于 2017-08-11 19:07:22
//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 }) ;https://stackoverflow.com/questions/45642066
复制相似问题