最近有人向我指出各种 Linq 扩展方法(例如 Where
、Select
等)返回一个 IEnumerable<T>
。这也恰好是 IDisposable
.以下评估为 True
new int[2] {0,1}.Select(x => x*2) is IDisposable
我需要处理 Where
的结果吗?表达?
每当我调用返回 IEnumerable<T>
的方法时,我是否(可能)承担在完成处理后调用 dispose 的责任?
最佳答案
不,你不需要担心这个。
他们返回 IDisposable
的事实implementation 是一个实现细节 - 这是因为 C# 编译器的 Microsoft 实现中的迭代器 block 碰巧创建了一个单一类型,它同时实现了 IEnumerable<T>
和 IEnumerator<T>
.后者扩展了 IDisposable
,这就是您看到它的原因。
示例代码来演示这一点:
using System;
using System.Collections.Generic;
public class Test
{
static void Main()
{
IEnumerable<int> foo = Foo();
Console.WriteLine(foo is IDisposable); // Prints True
}
static IEnumerable<int> Foo()
{
yield break;
}
}
请注意,您确实需要注意以下事实:IEnumerator<T>
工具 IDisposable
.所以任何时候你明确地迭代,你都应该正确地处理它。例如,如果你想遍历某些东西并确保你总是有 a 值,你可以使用类似这样的东西:
using (var enumerator = enumerable.GetEnumerator())
{
if (!enumerator.MoveNext())
{
throw // some kind of exception;
}
var value = enumerator.Current;
while (enumerator.MoveNext())
{
// Do something with value and enumerator.Current
}
}
(当然,foreach
循环会自动执行此操作。)
关于c# - 我是否需要考虑处置我使用的任何 IEnumerable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13459447/