Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#-如何从objectName创建泛型T?_C#_.net_Generics_System.reflection - Fatal编程技术网

c#-如何从objectName创建泛型T?

c#-如何从objectName创建泛型T?,c#,.net,generics,system.reflection,C#,.net,Generics,System.reflection,我创建了一个FetchData方法,它返回IList,并将objectName(string)作为参数(我们要返回列表的对象的名称) 如何从readbyquerysync方法的objectName中获取T?您不能“从objectName创建泛型T”,但可以从类型构造泛型方法 我认为您正在寻找的用法如下: // somehow get fully qualified name from objectName vat type = Type.GetType("fully qualified name

我创建了一个
FetchData
方法,它返回
IList
,并将
objectName(string)
作为参数(我们要返回列表的对象的名称)

如何从
readbyquerysync
方法的
objectName
中获取
T

您不能“从objectName创建泛型T”,但可以从类型构造泛型方法

我认为您正在寻找的用法如下:

// somehow get fully qualified name from objectName
vat type = Type.GetType("fully qualified name"); 
var mi = _gateway.GetType().GetMethod("ReadByQueryAsync").MakeGenericMethod(type);
并调用,例如:

mi.Invoke(_gateway, null)
或者使用构建lambda并缓存它

带有
可枚举的.First()的示例


你能添加一些代码吗?
typeof(T).Name
?如果我理解正确的话,另一种方法是不可能的。你不能
T
在编译时指定,而
objectName
在运行时提供。是否有理由需要使用字符串作为类型名称?@JohnathanBarclay我正在获取objectName作为API中的参数之一,该参数正在调用FetchData方法。我将尝试此方法
// somehow get fully qualified name from objectName
vat type = Type.GetType("fully qualified name"); 
var mi = _gateway.GetType().GetMethod("ReadByQueryAsync").MakeGenericMethod(type);
mi.Invoke(_gateway, null)
var mi = typeof(Enumerable)
    // cause multiple "First" methods
    .GetMethods()
    .Where(mi => mi.Name == "First" && mi.GetParameters().Length == 1)
    .First();
var type = Type.GetType("System.Int32");
var constructed = mi.MakeGenericMethod(type);
var obj = new[] { 1, 2 };
// you will have another order of parameters in Invoke if ReadByQueryAsync is instance method
var x = constructed.Invoke(
    null, // null cause First is extension method, should be obj if instance
    new[] { obj } // should be null for parameterless instance method
    ); // x = 1