linq - 动态地将类型传递给方法<T>

标签 linq entity-framework generics parameter-passing dynamically-generated

我有一个方法,它根据我传入参数的某种类型检索一些数据,如下所示:

    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/

相关文章:

c# - 获取不为空的属性名称

c# - 覆盖 SaveChanges() 的最佳方法

c# - Entity Framework 错误,额外的小数位

java - 如有必要,插入类型转换以保持类型安全

c# - 如何将通用类型参数的值转换为具体类型?

c# - 如何枚举匿名类型的集合?

c# - 内部连接上的 LINQ 查询错误

java - 如何在没有 "unchecked"警告的情况下转换为(已知)泛型类型?

c# - 动态表达式和动态字符串操作

c# - 通过字符串更改属性的状态