Program Tip

IEnumerable의 폐기를 고려해야합니까?

programtip 2020. 11. 5. 18:54
반응형

IEnumerable의 폐기를 고려해야합니까? 나는 사용한다?


최근에 (같은 다양한으로 LINQ 확장 메서드 나에게 지적되어있어 Where, Select등이,)를 반환 IEnumerable<T>도 일어나는이되고 IDisposable. 다음은 다음과 같이 평가됩니다.True

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

Where표현 결과를 폐기해야 합니까?

returning 메서드를 호출 할 때마다 IEnumerable<T>처리를 마쳤을 때 dispose 호출에 대한 책임을 (잠재적으로) 수락합니까?


아니요, 이것에 대해 걱정할 필요가 없습니다.

그들이 돌아 사실 IDisposable구현은 구현 세부입니다 - C # 컴파일러의 Microsoft 구현에 반복자 블록이 생성하는 일이 그것 때문에 하나 되는 구현 모두 유형 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. 따라서 명시 적으로 반복 할 때마다 적절하게 처리해야합니다. 당신은 당신이 항상해야하는 것이 무엇인가를 반복하고 확인하려는 경우 예를 들어, 값을, 당신이 뭔가를 같이 사용할 수 있습니다 :

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물론 루프는이 작업을 자동으로 수행합니다.)

참고 URL : https://stackoverflow.com/questions/13459447/do-i-need-to-consider-disposing-of-any-ienumerablet-i-use

반응형