[英]What is the best way to return two lists in C#?
我几乎不好意思问这个问题,但作为很长一段时间的C程序员,我觉得也许我不知道在C#中做到这一点的最好方法。
我有一个成员函数,我需要返回两个自定义类型List<MyType>
( List<MyType>
),我事先知道我将始终只返回其中两个列表的返回值。
显而易见的选择是:
public List<List<MyType>> ReturnTwoLists();
要么
public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);
两者似乎都不是最优的。
关于如何改进这个的任何建议?
第一种方法没有在语法中明确表示只返回2个列表,第二种方法使用引用而不是返回值,这看起来非c#。
首先,这可能应该out
,而不是ref
。
其次,您可以声明并返回包含两个列表的类型。
第三,你可以声明一个通用的Tuple
并返回一个实例:
class Tuple<T,U> {
public Tuple(T first, U second) {
First = first;
Second = second;
}
public T First { get; private set; }
public U Second { get; private set; }
}
static class Tuple {
// The following method is declared to take advantage of
// compiler type inference features and let us not specify
// the type parameters manually.
public static Tuple<T,U> Create<T,U>(T first, U second) {
return new Tuple<T,U>(first, second);
}
}
return Tuple.Create(firstList, secondList);
您可以针对不同数量的项目扩展此想法。
归还这个:
public class MyTwoLists {
public List<MyType> ListOne {get;set;}
public List<MyType> ListTwo {get;set;}
}
你的第一个建议不是两个清单。 这是一份清单清单。
第二个选项会按照您的意图执行,但您可能希望将其更改为使用out关键字而不是ref,这样您的方法的调用者就会知道您正在做什么的意图。
public void ReturnTwoLists(out List<MyType> listOne, out List<myType> listTwo);
你有几个选择:
如果列表按顺序无意义,请使用一对:
public Pair<List<MyType>,List<MyType> ReturnTwoLists()
{
return new Pair(new List<MyType(), new List<MyType());
}
如上所述,您可以使用out或ref参数。 如果一个列表比另一个列表更有意义,这是一个很好的选择。
如果客户端知道密钥,或者想要查找它们的工作,您可以使用字典:
public Dictionary<string,List<MyType> ReturnTwoLists()
{
Dictionary<string,List<MyTpe>> d = new Dictionary<string,List<MyType>>();
d.Add("FirstList",new List<MyType>());
d.Add("SecondList",new List<MyType>());
return new Dictionary()(new List<MyType(), new List<MyType());
}
或者,对于完整性和一致性而言,我眼中最“正确”的解决方案是创建一个简单的数据容器类来保存两个列表。 这为消费者提供了强类型,良好的静态编译(读取:intellisense-enabled)返回值。 该类可以嵌套在该方法旁边。
创建一个包含两者的简单结构并将其作为函数的输出返回?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.