我是否需要考虑任何的IEnumerable&LT处置; T>我用? [英] Do I need to consider disposing of any IEnumerable<T> I use?

查看:136
本文介绍了我是否需要考虑任何的IEnumerable&LT处置; T>我用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它最近已经向我指出的各种LINQ的扩展方法(如其中,选择等)返回的IEnumerable< T> 这也恰好是的IDisposable 。下面的计算结果为

It's recently been pointed out to me that various Linq extension methods (such as Where, Select, etc) return an IEnumerable<T> that also happens to be IDisposable. The following evaluates to True

new int[2] {0,1}.Select(x => x*2) is IDisposable

我是否需要处置一个其中,表达式的结果?

Do I need to dispose of the results of a Where expression?

每当我打电话回的IEnumerable℃的方法; T> ,我是(可能)承担责任调用处理时,我用它完成了吗?

Whenever I call a method returning IEnumerable<T>, am I (potentially) accepting responsibility for calling dispose when I've finished with it?

推荐答案

没有,你不必担心这一点。

No, you don't need to worry about this.

他们返回的IDisposable 执行情况的事实是一个实现细节 - 这是因为微软执行的C#编译器的迭代器块发生创建的它实现类型都的IEnumerable< T> 的IEnumerator< T> 。 ,后者扩展的IDisposable ,这就是为什么你看到它

The fact that they return an IDisposable implementation is an implementation detail - it's because iterator blocks in the Microsoft implementation of the C# compiler happen to create a single type which implements both IEnumerable<T> and IEnumerator<T>. The latter extends IDisposable, which is why you're seeing it.

示例代码来演示这一点:

Sample code to demonstrate this:

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 。所以,你明确地迭代任何时候,你应该妥善处置。例如,如果你想遍历的东西,并确保您始终的的值,可以使用这样的:

Note that you do need to take note of the fact that IEnumerator<T> implements IDisposable. So any time you iterate explicitly, you should dispose of it properly. For example, if you want to iterate over something and be sure that you'll always have a value, you might use something like:

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
    }
}

(A 的foreach 循环会自动做到这一点,当然)。

(A foreach loop will do this automatically, of course.)

这篇关于我是否需要考虑任何的IEnumerable&LT处置; T&GT;我用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆