2017-08-24 44 views
0

我有这个功能我怎么能发送类型的功能

public IList<TEntity> GetData<TEntity>() where TEntity : class 
    { 
     return _DbContext.Set<TEntity>().ToList(); 
    } 

,我所以现在我有从字符串动态加载类View_Export_Books调用这个函数像这样

GetData<View_Export_Books>() 

。这可能吗?

感谢您的任何帮助。

添加注释:

我View_Export_Books为字符串,我想将其转换为一个通用的参数。

+0

你到底在问什么?你是否想要一种将泛型参数转换为字符串的方法?或者如何改变方法不使用泛型并接受字符串作为参数呢? – Sweeper

+2

[我如何使用反射来调用泛型方法?](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) – thehennyy

+0

我有View_Export_Books作为字符串,我想将其转换为通用参数。 – user1861065

回答

0

我希望它能帮助你。如果您有任何问题,请告诉我。

public class MyClass 
    { 
     public IList<TEntity> GetData<TEntity>() where TEntity : class 
     { 
      return _DbContext.Set<TEntity>().ToList(); 
     } 

     public void Test() 
     { 
      var type = GetTypeOf("View_Export_Books"); 
      var method = typeof(MyClass).GetMethod("GetData").MakeGenericMethod(type); 

      //This was a mistake. 
      //var instance = Activator.CreateInstance(type); 

      method.Invoke(this/*instance*/, new object[]{ }); 
     } 

     private Type GetTypeOf(string className) 
     { 
      var assembly = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetTypes().Any(t => t.Name == className)); 
      return assembly.GetTypes().First(t => t.Name == className); 
     } 
    } 
+0

嗨,感谢您的帮助,但出现以下错误:对象与目标类型不匹配。 on方法。调用(实例,新对象[]); – user1861065

+0

@ user1861065,对不起,我的坏。该实例不正确。我已经改变它,你可以看到错误的部分作为评论。 –

+0

准确地说,我结束了这个......感谢您的帮助! – user1861065