在C#中返回两个列表的最佳方式是什么?

栏目: ASP.NET · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自: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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head First PHP & MySQL

Head First PHP & MySQL

Lynn Beighley、Michael Morrison / O'Reilly Media / 2008-12-29 / USD 44.99

If you're ready to create web pages more complex than those you can build with HTML and CSS, Head First PHP & MySQL is the ultimate learning guide to building dynamic, database-driven websites using P......一起来看看 《Head First PHP & MySQL》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具