gpt4 book ai didi

c# - OOC : What is the difference between ToList() and casting to List in . 网络?

转载 作者:太空狗 更新时间:2023-10-29 18:14:28 24 4
gpt4 key购买 nike

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();
}

最佳答案

ToList()与(转换)到 List 不同。

ToList()取任何IEnumerable (列表、数组、字典、集合等)并将其转换为 List .

转换为 List接受一个已经是某种列表的对象,并将其标记为列表。示例:

// 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 .请记住,它必须支持生成器(延迟求值),因此将它作为下面的列表是没有意义的。

顺便说一句,你看过内置函数Enumerable.Range了吗? ?

关于c# - OOC : What is the difference between ToList() and casting to List<T> in . 网络?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2107115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com