【问题标题】:C# multiple generic types in method input and output collectionC#方法输入输出集合中的多个泛型类型
【发布时间】:2021-09-07 12:31:38
【问题描述】:

我有如下所示的通用查询方法

List<T> Query<T>(QueryModel query) where T : BaseClass 
{
      // get data and Deserialize by T
}

// where T is Table DTO, to Deserialize response by T

现在我想并行实现多个查询执行

为此,我需要有多个类型参数作为响应和输入,并希望实现这样的目标:

List<T1, T2, T3> Query<T1, T2, T3>(List<QueryModel> queries) 
     where T1: BaseClass,
     where T2: BaseClass,
     where T3: BaseClass 
{
     // for each query in queries
     // get data for each query and 
     // deserialize each by T1/T2/T3 accordingly
     // return all responses in single generic collection
}

在上面的示例中可以有 3 个查询,每个查询都可以通过提供的类型参数相应地反序列化。

但我相信对于 List 之类的集合,我们不能有多个类型的参数,不确定如何实现。

PS:我现在可以使用有限的表集进行查询,例如使用 3-4 个类型化参数进行查询,因此可以添加固定数量的类型化参数的重载,如果 n 数有一些解决方案会很棒类型参数。

【问题讨论】:

  • 如果您的意图是将所有结果放入一个列表中,那么显而易见的是返回List&lt;BaseClass&gt;。但是你没有给出关于你在做什么的很多细节,所以前面只是一个猜测
  • 如果目标是并行查询,为什么不直接调用不同类型的第一个查询呢?

标签: c# generics generic-list generic-collections


【解决方案1】:

你可以这样写

(T1 r1, T2 r2, T3 r3) Query<T1, T2, T3>(QueryModel q1,QueryModel q2,QueryModel q3 )

这将不允许任意数量的查询,但无论如何你不能拥有可变数量的泛型参数,所以我看不出有任何方法可以在保留泛型类型的同时做到这一点。

【讨论】:

    【解决方案2】:

    从 C# 7.0 开始,我相信您可以使用元组,例如

        List<(T1, T2, T3)> Get<T1,T2,T3>(string query) where T1 : BaseClass, new() where T2 : BaseClass, new() where T3 : BaseClass, new()
        {
            var result = new List<(T1, T2, T3)>
            {
                ( new T1(), new T2(), new T3()),
                ( new T1(), new T2(), new T3())
    
            };
    
            return result; 
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多