【发布时间】:2011-01-07 14:31:34
【问题描述】:
OOC:出于好奇
因此,作为一个小练习和学习的目的,我决定检查我是否能够实现一个非常基本的递归函数,该函数将返回 List<int>,但有以下限制:
1- 结果应该由函数本身返回(而不是作为参数传递给void 函数)。
2 - 函数体中没有声明局部“命名”变量。
我想出了下面的解决方案(顺便说一句:这可以通过任何方式改进吗?)
在执行此操作时,我了解到 ToList() 与投射到 List<T> 不同(请参见下面的示例) - 任何可以解释幕后发生的事情以及两者之间的区别是什么的人?
谢谢!
PS - 我使用的是 4.0 版(以防万一)。
编辑:运行时错误是Unable to cast object of type '<ConcatIterator>d__71'1[System.Int32]' to type 'System.Collections.Generic.List'1[System.Int32]'
public static List<int> SomeIntegers(int min, int max)
{
//assume max >= min for simplicity
if (min == max)
return new List<int>() { min };
// runtime error
//return (List<int>)(SomeIntegers(min, max - 1).Concat(new List<int>() { max }));
//works
return (SomeIntegers(min, max - 1).Concat(new List<int>() { max })).ToList();
}
【问题讨论】:
标签: c# collections casting