Jer*_*ite 16 c# coding-style list
我几乎不好意思问这个问题,但作为很长一段时间的C程序员,我觉得也许我不知道在C#中做到这一点的最好方法.
我有一个成员函数,我需要返回两个自定义类型(List<MyType>)的列表,我事先知道,我将始终只有两个这样的列表的返回值.
显而易见的选择是:
public List<List<MyType>> ReturnTwoLists();
Run Code Online (Sandbox Code Playgroud)
要么
public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);
Run Code Online (Sandbox Code Playgroud)
两者似乎都不是最优的.
关于如何改进这个的任何建议?
第一种方法并没有在语法中明确表示只返回2个列表,第二种方法使用引用而不是返回值,这看起来非c#.
Meh*_*ari 31
首先,这应该是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);
Run Code Online (Sandbox Code Playgroud)
您可以针对不同数量的项目扩展此想法.
Joh*_*ers 24
归还这个:
public class MyTwoLists {
    public List<MyType> ListOne {get;set;}
    public List<MyType> ListTwo {get;set;}
}
Run Code Online (Sandbox Code Playgroud)