【问题标题】:c# return both list of string and list of generic typec# 同时返回字符串列表和泛型列表
【发布时间】:2022-01-07 15:21:23
【问题描述】:

我需要从一个函数返回多个项目。我该怎么做?

public List<string> GetInfo()
{
    var result = new List<string>();

    return result;
}

我怎样才能退回这样的东西?基本上是字符串列表,也可能是泛型类型列表。

public List<string> GetInfo()
{
    var result = new List<string>();

    return result and someType;
}

public class someType
{
    public List<SomeOthertype> someOthertype { get; set; }
}

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    如果我理解正确,您可以尝试使用命名元组

    public (List<string> result, List<SomeOthertype> other) GetInfo()
    {
        var result = new List<string>();
    
        someType instance = new someType();
    
        //TODO: put relevant code here
    
        // we return both result and someOthertype in one tuple 
        return (result, instance.someOthertype);
    }
    

    用法:

    var info = GetInfo();
    
    var result = info.result;
    var other = info.other;
    

    【讨论】:

      【解决方案2】:

      我建议使用generic method 以便可以使用不同的类型:

      public static (List<string>, List<U>) GetInfo<U>()
      {
          var list = new List<string>();
          var another = new List<U>();
          //...
          return (list, another);
      }
      

      【讨论】:

        【解决方案3】:

        从 c# 7 开始,tuple value types 是从函数返回多个值的最简洁方式。

        Pre c# 7 你可以使用out parameters

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-16
          • 2011-07-20
          • 1970-01-01
          • 2019-08-05
          • 2020-09-05
          • 1970-01-01
          • 2010-11-05
          • 1970-01-01
          相关资源
          最近更新 更多