gpt4 book ai didi

c# - WhereListIterator.ToList() 的实现

转载 作者:行者123 更新时间:2023-11-30 15:33:09 25 4
gpt4 key购买 nike

像这样的一段代码

List<int> foo = new List<int>() { 1, 2, 3, 4, 5, 6 };
IEnumerable<int> bar = foo.Where(x => x % 2 == 1);

bar类型为 System.Linq.Enumerable.WhereListIterator<int>由于延迟执行。因为它实现了 IEnumerable<int>可以将其转换为 List<int>使用 ToList() .但是,我一直无法识别在 ToList() 时运行的代码的某些部分。叫做。我正在使用 dotPeek 作为反编译器,这是我第一次尝试这样的事情,如果我在途中犯了任何错误,请纠正我。

我将在下面描述到目前为止我发现的内容(所有程序集都是版本 4.0.0.0):

  1. Enumerable.WhereArrayIterator<TSource>在文件 Enumerable.cs 中实现命名空间 System.Linq在装配System.Core .该类既没有定义 ToList()本身也不实现 IEnumerable<TSource> .它实现了 Enumerable.Iterator<TSource>它位于同一个文件中。 Enumerable.Iterator<TSource>执行IEnumerable<TSource> .

  2. ToList()是一个扩展方法,也位于 Enumerable.cs 中.它所做的只是空检查,然后调用 List<TSource> 的构造函数。及其论点。

  3. List<T>在文件 List.cs 中定义命名空间 System.Collections.Generic在装配mscorlib . ToList() 调用的构造函数有签名public List(IEnumerable<T> collection) .它再次进行空检查,然后将参数转换为 ICollection<T> .如果集合没有元素,它会创建一个空数组的新列表,否则它使用 ICollection.CopyTo()创建新列表的方法。

  4. ICollection<T>mscorlib 中定义\System.Collections.Generic\ICollection.cs .它实现了 IEnumerable通用和非通用形式。

这就是我卡住的地方。都不是 Enumerable.WhereArrayIterator<TSource>也不Enumerable.Iterator<TSource>实现 ICollection ,所以在某个地方,必须进行强制转换,我无法找到在 CopyTo() 时运行的代码被称为。

最佳答案

这是 List<T> constructor 中的相关部分(ILSpy):

ICollection<T> collection2 = collection as ICollection<T>; // this won't succeed
if (collection2 != null)
{
int count = collection2.Count;
this._items = new T[count];
collection2.CopyTo(this._items, 0);
this._size = count;
return;
}
// this will be used instead
this._size = 0;
this._items = new T[4];
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext())
{
this.Add(enumerator.Current);
}
}

所以你看到了collection as ICollection<T>;尝试转换为 ICollection<T> , 如果有效 CopyTo将被使用,否则序列将被完全枚举。

你的 WhereListIterator<int>是一个查询 而不是一个集合,所以它不能转换为 ICollection<T> , 因此它将被枚举。

关于c# - WhereListIterator.ToList() 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17726863/

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