我有一个方法,它根据我传入参数的某种类型检索一些数据,如下所示:
protected void FillList<TEntity>()
{
doWorkForTEntity();
}
我需要动态调用此方法:
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
FillList<currentEntity>();
我收到此错误:
The type or namespace name 'currentEntity' could not be found (are you missing a using directive or an assembly reference?)
我尝试过中间对象类型,但没有成功
请问有什么想法吗?
最佳答案
由于编译时没有有关实体类型的信息,因此需要通过反射构造并调用适当的方法:
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
var method = this.GetType().GetMethod("FillList", BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(currentEntity);
method.Invoke(this, new object[0]);
关于linq - 动态地将类型传递给方法<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16338669/