OOC:ToList()和强制转换为List< T>有什么区别?在.NET中? [英] OOC: What is the difference between ToList() and casting to List<T> in .NET?
问题描述
OOC:出于好奇
因此,作为一次小运动,为了学习,我决定检查我是否能够实现非常基本的递归该函数将返回 List< int>
,但具有以下限制:
So, as a little exercise and for the sake of learning, I decided to check if I was able to implement a very basic recursive function that would return a List<int>
, but with the following restrictions:
1-结果应为由函数本身返回(而不是作为参数传递给 void
函数)。
1- The result should be returned by the function itself (as opposed to passed as an argument to a void
function).
2-否在函数的主体中声明的局部命名变量。
2 - No local "named" variables declared in the function's body.
我想出了以下解决方案(顺便说一句:这可以通过任何方式加以改进吗?)
I came up with the solution below (BTW: can this be improved in any way?)
在执行此操作时,我了解到 ToList()
与强制转换为 List< T> ;
(请参见下面的示例)-可以解释幕后情况的人以及两者之间的区别是什么?
While doing this, I learnt that ToList()
is not the same thing as casting to List<T>
(see example below) - Anyone out there who can explain what happens under the hood and what the difference between the two is?
谢谢!
PS-我使用的是4.0版本(以防万一)。
PS - I'm using version 4.0 (in case it matters).
编辑:运行时错误是无法类型为'< ConcatIterator> d__71'1 [System.Int32]'的st对象,以类型为'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();
}
推荐答案
ToList与(广播)到列表。
ToList is not the same as (casting) to List.
ToList使用任何IEnumerable(列表,数组,字典,集合等)并将其转换为列表。
ToList takes any IEnumerable (lists, arrays, Dictionaries, Sets, etc) and turns it into a list.
投射到列表会使用已经是某种形式的列表的对象,并将其标记为列表。示例:
Casting to List takes an object that is already a list of some sort, and labels it as a list. example:
// fail -- arrays are not lists
var not_a_list = (List<int>)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<WorkflowRole>
var derived_from_list = (List<WorkflowRole>) new WorkflowRoleCollection();
在您的情况下,Concat返回IEnumerable,而不是List。请记住,它必须支持生成器(它们是经过延迟评估的),因此将其像下面的列表一样毫无意义。
In your case, Concat returns an IEnumerable, and not a List. Remember that it has to support generators (which are lazy-evaluated), so it doesn't make sense for it to be anything like a list underneath.
Btw您查看了内置函数 Enumerable.Range
?
Btw, have you taken a look at the built-in function Enumerable.Range
?
这篇关于OOC:ToList()和强制转换为List< T>有什么区别?在.NET中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!