在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