OOC:ToList()和.NET中的List 之间有什么区别?
OOC:出于好奇
所以,作为一个小练习,为了学习,我决定检查我是否能够实现一个非常基本的递归函数,它将返回一个List
,但有以下限制:
1-结果应该由函数本身返回(而不是作为参数传递给void
函数)。
2 – 在函数体中声明没有本地“命名”变量。
我想出了下面的解决方案(顺便说一句:这可以以任何方式改进吗?)
在这样做的过程中,我了解到ToList()
与ToList()
List
(见下面的例子) – 那里的任何人都可以解释幕后发生的事情以及两者之间的区别是什么?
谢谢!
PS – 我正在使用4.0版(如果它很重要)。
编辑:运行时错误是Unable to cast object of type 'd__71'1[System.Int32]' to type 'System.Collections.Generic.List'1[System.Int32]'
public static List SomeIntegers(int min, int max) { //assume max >= min for simplicity if (min == max) return new List() { min }; // runtime error //return (List)(SomeIntegers(min, max - 1).Concat(new List() { max })); //works return (SomeIntegers(min, max - 1).Concat(new List() { max })).ToList(); }
ToList与List(铸造)不同。
ToList接受任何IEnumerable(列表,数组,字典,集合等)并将其转换为列表。
Casting to List会获取一个已经是某种列表的对象,并将其标记为列表。 例:
// fail -- arrays are not lists var not_a_list = (List)int[]; // success: arrays *are* IEnumerable, so you can convert them to a list. var list_from_array = new [] { 1,2,3,4,5 }.ToList(); // success: WorkflowRoleCollection derives from List var derived_from_list = (List ) new WorkflowRoleCollection();
在您的情况下,Concat返回IEnumerable,而不是List。 请记住,它必须支持生成器(它们是惰性评估的),所以它就像下面的列表一样没有意义。
顺便问一下,你看看内置函数Enumerable.Range
吗?
- 仅当您实际拥有
List
,从List
派生的内容或具有有效类型转换为List
,才能进行InvalidCastException
,否则会因InvalidCastException
而失败。ToList()
适用于任何IEnumerable。 - 即使您已有列表,
ToList()
始终创建列表的新副本。 将某些内容转换为List
通常不会生成列表的副本 – 它只为您提供了同一对象的新编译时类型。
顺便说一句,生成整数列表的最佳方法是:
Enumerable.Range(min, length);
要么
Enumerable.Range(min, max-min+1);
但这并不能帮助你学习,所以对你赞不绝口! 🙂