内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/1099134/what-is-the-best-way-to-return-two-lists-in-c
我几乎很尴尬地提出这个问题,但是作为一个很长的时间,C程序员,我觉得也许我不知道在C#中最好的做法.
我有一个成员函数,我需要返回一个自定义类型(List<MyType>)的两个列表,并且我事先知道,我将始终只有这两个列表的返回值.
明显的选择是:
public List<List<MyType>> ReturnTwoLists();
要么
public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);
两者似乎都不是最佳的.
有什么建议如何改善这个?
第一种方式在语法中并不清楚只返回2个列表,而第二种方法使用引用而不是返回值,这似乎非常简单.
首先,这应该是出来,而不是参考.
其次,您可以声明并返回一个包含两个列表的类型.
第三,你可以声明一个通用的元组,并返回一个实例:
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);
您可以对不同数量的项目扩展这个想法.
代码日志版权声明:
翻译自:http://stackoverflow.com/questions/1099134/what-is-the-best-way-to-return-two-lists-in-c
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- C# 永远不会返回的方法真的不会返回
- iOS之导航返回上上个控制器或指定返回某个控制器
- 如何在Hibernate/JPA中配置具有两个连接池的两个数据源
- MyBatis返回Map
- (译)从路由返回数据
- c++ 为什么在返回从函数的返回类型派生的类型的本地对象时,没有选择move构造函数?
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。