簡體   English   中英

在C#中返回兩個列表的最佳方法是什么?

[英]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());
 }

如上所述,您可以使用outref參數。 如果一個列表比另一個列表更有意義,這是一個很好的選擇。

如果客戶端知道密鑰,或者想要查找它們的工作,您可以使用字典:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM