无法调用 Invoke()
Can't call Invoke()
我正在尝试调用 Invoke()
但它总是抛出:
Object does not match target type
我不确定要传递什么作为第一个参数 - 假设这是问题所在 - 我已经尝试了很多东西但没有成功。下面是我的代码:
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
class 是:
public class City : Entity
而Entity
是一个抽象class:
public abstract class Entity
作为第一个 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 }) ;
我正在尝试调用 Invoke()
但它总是抛出:
Object does not match target type
我不确定要传递什么作为第一个参数 - 假设这是问题所在 - 我已经尝试了很多东西但没有成功。下面是我的代码:
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
class 是:
public class City : Entity
而Entity
是一个抽象class:
public abstract class Entity
作为第一个 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 }) ;