1、具体是什么意思?
为了掌握这一点,了解它是什么IEnumerable<T>或它代表什么可能会有所帮助。文档中的定义是:
公开枚举器,它支持对指定类型的集合进行简单迭代
在您的情况下IEnumerable<IEnumerable<int>>,定义基本上可以翻译为:
[...] 支持对IEnumerable<int>s 集合的简单迭代,每个 s 都支持对整数集合的简单迭代
这导致可以由“集合集合”表示的嵌套迭代行为。帕斯卡三角形就是一个很好的例子,因为你有这个:
[ // Outer collection
[1], // Inner collection 1
[1,1], // Inner collection 2
[1,2,1], // Inner collection 3
... // Inner collection n
]
代码中的一个例子是:
IEnumerable<int> innerCollection1 = new List<int> { 1 };
IEnumerable<int> innerCollection2 = new List<int> { 1, 1 };
IEnumerable<int> innerCollection3 = new List<int> { 1, 2, 1 };
IEnumerable<IEnumerable<int>> outerCollection = new List<IEnumerable<int>>
{
innerCollection1,
innerCollection2,
innerCollection3
};
然后要获取内部的实际值,您需要遍历外部集合中的每个内部集合。例如:
foreach (IEnumerable<int> innerCollection in outerCollection)
{
foreach (int value in innerCollection)
{
Console.Write(value);
Console.Write(" ");
}
Console.WriteLine();
}
输出为:
1
1 1
1 2 1
2、Calculate方法的返回类型应该是什么?
在 C# 中,您可以使用任何实现 的东西来表示它IEnumerable<int>,例如列表列表:
new List<List<int>>
{
new List<int> { 1 },
new List<int> { 1, 1 },
new List<int> { 1, 2, 1 },
// new List<int> { ... },
}
或数组数组:
new int[][]
{
new int[] { 1 },
new int[] { 1, 1 },
new int[] { 1, 2, 1 },
// new int[] { ... },
}
或数组列表:
new List<int[]>
{
new int[] { 1 },
new int[] { 1, 1 },
new int[] { 1, 2, 1 },
// new int[] { ... },
}
或列表数组:
new List<int>[]
{
new List<int> { 1 },
new List<int> { 1, 1 },
new List<int> { 1, 2, 1 },
// new List<int> { ... },
}
等等等等
3、虽然Calculate方法不是继承自IEnumerable接口,但是否应该实现IEnumerable.GetEnumerator()?
您只需要在IEnumerable.GetEnumerator()实现接口的自定义类型中实现即可IEnumerable。在您的情况下,您可以只返回一个已经实现该接口的类型( System.Collections.Generic中的几乎所有内容),如上所示。您显然只需要根据rows传递给方法的数量动态构建该实例,一个简单的示例看起来像:
public static IEnumerable<IEnumerable<int>> Calculate(int rows)
{
List<List<int>> outerList = new List<List<int>>();
for (int i = 0; i < rows; i++)
{
List<int> innerList = new List<int>();
// logic to build innerList
outerList.Add(innerList);
}
return outerList;
}
调用时,将例如 3 传递为rows,应导致:
List<List<int>> outerList = new List<List<int>>
{
new List<int> { 1 }, // innerList 1
new List<int> { 1, 1 }, // innerList 2
new List<int> { 1, 2, 1 } // innerList 3
}