反思和小巧玲珑

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

我正在尝试将我的类映射到特定属性,然后是 Dapper 的 QueryAsync< T > 但是,由于我不知道 < T > 泛型参数,我正在尝试根据运行时类型变量调用 QueryAsync 返回 IEnumerable< T >。可能吗?

我尝试使用 QueryAsync 的方法重载

Task<IEnumerable<object>> QueryAsync(this IDbConnection cnn, Type type, string sql)

它返回 IEnumerable< object>,但我需要返回“< reportType > 的 IEnumerable” reportType 是一个 Type 对象,我知道不可能将泛型与变量一起使用,这只是示例

private static IEnumerable<Type> GetMyReports(Assembly assembly)
{
    foreach (Type type in assembly.GetTypes())
    {
        if (type.GetCustomAttributes(typeof(MapReportAttribute), true).Length > 0)
        {
            yield return type;
        }
    }
}

var myReports = GetMyReports(myAssembly).ToList();

foreach(Type reportType in myReports)
{
  using var con = new NpgsqlConnection(_configuration.GetConnectionString("..."));

  var rows = await con.QueryAsync(reportType , ".. query ..");

  //rows is IEnumerable<object>. Is it possible with some method of Dapper, return """IEnumerable<reportType>""" ???
}
c# generics reflection dapper
1个回答
0
投票

一个可能的解决方案是制作您自己的通用包装方法以切换到您知道 T 的上下文。

var myReports = GetMyReports(myAssembly).ToList();
var method = typeof("your class").GetMethod("QueryWrapperAsync", BindingFlags.Static | BindingFlags.NonPublic);

foreach(Type reportType in myReports)
{
    var genericMethod = method.MakeGenericMethod(reportType);
    genericMethod.Invoke(null, null);
}
    
private static async Task QueryWrapperAsync<T>()
{
    using var con = new NpgsqlConnection(_configuration.GetConnectionString("..."));
    var rows = await con.QueryAsync<T>(".. query ..");
    //do stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.