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