问题描述
我几乎不好意思问这个问题,但很长一段时间的C程序员,我觉得,也许我不知道在C#中做到这一点的最好办法。
I am almost embarrassed to ask this question, but as a long time C programmer I feel that perhaps I am not aware of the best way to do this in C#.
我有我需要返回自定义类型的两个列表的成员函数(列表< MyType的>
),我事先知道我将永远有一个返回值。只有两种这些名单
I have a member function that I need to return two lists of a custom type (List<MyType>
) and I know beforehand that I will always have a return value of only two of these lists.
最明显的选项是:
public List<List<MyType>> ReturnTwoLists();
或
public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo);
两者似乎非最优
Both seem to be non-optimal.
关于如何提高这个有什么建议?
Any suggestions on how to improve this?
第一种方法并不能使它在正在返回只有2列出的语法清晰,第二个使用引用而不是一个返回值,这似乎让非C#。
The first way doesn't make it clear in the syntax that only 2 lists are being returned, and the second uses references rather then a return value, which seem so non-c#.
推荐答案
首先,这大概应该是退出
,而不是 REF
。
First of all, that should probably be out
, not ref
.
第二,你可以声明并返回。键入包含两个列表
Second, you can declare and return a type containing the two lists.
第三,你可以声明泛型元组
键,返回的是一个实例:
Third, you can declare a generic Tuple
and return an instance of that:
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);
您可以扩展这个想法不同数量的物品。
You can extend this idea for different number of items.
这篇关于什么是用C#返回两个列表的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!