Reflection T的Ienumerable,T仅在运行时可用

Reflection T的Ienumerable,T仅在运行时可用,reflection,ienumerable,Reflection,Ienumerable,我有一个带有这个签名的方法 public IEnumerable<T> GetAll<T>() where T : new() { // Orm Lite Version return Connection.LoadSelect<T>(); } public IEnumerable GetAll(),其中T:new() { //Orm精简版 返回连接。LoadSelect(

我有一个带有这个签名的方法

 public IEnumerable<T> GetAll<T>() where T : new()
        {
            // Orm Lite Version 
            return Connection.LoadSelect<T>();

        }
public IEnumerable GetAll(),其中T:new()
{
//Orm精简版
返回连接。LoadSelect();
}
在编译时,我不知道类型t。我只知道运行时的类名。是否可以使用类似这样的反射调用此方法

string TargetTBLName = ...;//TargetTBLName get's it's value at runtime
Type ParentTableClass = Type.GetType(TargetTBLName);
IEnumerable<Type.GetType(TargetTBLName)> test = Repository.GetAll<Type.GetType(TargetTBLName)>();
字符串targetBlName=//targetBlName在运行时获取它的值
类型ParentTableClass=Type.GetType(targetBlName);
IEnumerable test=Repository.GetAll();

有什么想法吗?

我想试试动态图书馆。你可以用很多不同的方法来做,但我更喜欢这个,因为它简单。你可以找到它

请记住,如果
存储库
是静态的,则必须稍微调整它以使用静态调用上下文(查找链接)

现在您有了一个
测试
对象,它是一个
动态
——您可以将它与duck键入一起使用(例如,这对速度有一些影响),但一般来说,您可以对普通的
IEnumerable
执行任何您想执行的操作

如果要使用反射,请执行以下操作:

MethodInfo getAll= typeof(Repository).GetMethod("GetAll");
MethodInfo getAllGeneric= getAll.MakeGenericMethod(ParentTableClass);
object result = getAllGeneric.Invoke(this, null); 
            //or null, null is Repository is static
var finalObject = result as IEnumerable;

请注意,由于此
ParentTableClass
在编译过程中是未知的,因此您将无法访问实际类型提供的任何内容,除非您使用
动态
方法。

我猜这一行中存在键入错误MethodInfo getAllGeneric=method.MakeGenericMethod(ParentTableClass);我使用了你的第二种方法,效果很好。使用第一种方法的优缺点是什么?对于第二种方法,您不能使用
finalObject
元素的特定属性,因为它们只是
object
类型。如果你想的话,当然可以投。第一个使用了DLR的一些非常酷的特性——它基本上是在运行时创建代码,就像手动键入的代码一样。它会更快一点(尽管通常这并不重要),并且它会给您留下动态对象,让您具有“鸭子打字”的能力。因此,您可以编写
myObjectFromCollection.BogusMethod()
,它将进行编译。如果该方法存在,它将工作。否则,它将崩溃;-)如果你喜欢我的答案,请投赞成票和/或接受为好答案。当然,如果你想知道任何更具体的细节,可以直接问:)我不能投赞成票。我是一个新用户,声誉很低:(
MethodInfo getAll= typeof(Repository).GetMethod("GetAll");
MethodInfo getAllGeneric= getAll.MakeGenericMethod(ParentTableClass);
object result = getAllGeneric.Invoke(this, null); 
            //or null, null is Repository is static
var finalObject = result as IEnumerable;