简体   繁体   English

为什么Enumerable.Range实现IDisposable?

[英]Why does Enumerable.Range Implement IDisposable?

Just wondering why Enumerable.Range implements IDisposable . 只是想知道为什么Enumerable.Range实现了IDisposable

I understand why IEnumerator<T> does, but IEnumerable<T> doesn't require it. 我理解为什么IEnumerator<T>会这样做,但IEnumerable<T>不需要它。


(I discovered this while playing with my .Memoise() implementation, which has statement like (我在玩我的.Memoise()实现时发现了这个,它的声明就像

if (enumerable is IDisposable)
    ((IDisposable)enumerable).Dispose();

in its "source finished" method that I had placed a breakpoint on out of curiousity, and was triggered by a test.) 在它的“源完成”方法中,我因为好奇而放置了一个断点,并且是通过测试触发的。)

Enumerable.Range uses yield return in its method body. Enumerable.Range在其方法体中使用yield return The yield return statement produces an anonymous type that implements IDisposable , under the magic of the compiler, like this: yield return语句在编译器的魔力下生成一个实现IDisposable的匿名类型,如下所示:

static IEnumerable<int> GetNumbers()
{
    for (int i = 1; i < 10; i += 2)
    {
        yield return i;
    }
}

After being compiled, there is an anonymous nested class like this: 在编译之后,有一个匿名的嵌套类,如下所示:

[CompilerGenerated]
private sealed class <GetNumbers>d__0 
   : IEnumerable<int>, IEnumerable, IEnumerator<int>, IEnumerator, IDisposable
{
    //the implementation
    //note the interface is implemented explicitly
    void IDisposable.Dispose() { }
}

so the result is a IDisposable . 所以结果is IDisposable In this example, the Dispose method leaves empty. 在此示例中, Dispose方法保留为空。 I think the reason is that there is nothing need to be disposed. 我认为原因是没有必要处理。 If you yield return a type that contains unmanaged resources, you may get a different compiling result. 如果您yield return包含非托管资源的类型,则可能会得到不同的编译结果。 (NOT SURE about it) (不确定)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM