c#-如何从objectName创建通用T?

问题描述 投票:-1回答:1

我创建了一个FetchData方法,该方法返回IList<object>,并且它以objectName(string)作为参数(要返回其列表的对象的名称)。

Task<IList<object>> FetchData(string processGuiId, string objectName);

我正在从FetchData(string processGuiId, string objectName)调用网关方法以从源获取数据。

_gateway.ReadByQueryAsync<T>();

如何使用T方法从objectName中获取ReadByQueryAsync

c# .net generics system.reflection
1个回答
0
投票

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

我认为您正在寻找MethodInfo.MakeGenericMethod使用情况,例如:

MethodInfo.MakeGenericMethod

例如致电:

// 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并缓存它。

[expression trees的示例:

Enumerable.First()
© www.soinside.com 2019 - 2024. All rights reserved.