我可以在yield-return-method中使用“ using”吗?

问题描述 投票:0回答:1

[我刚刚看了一个YouTube视频,在该视频中,导师使用了yield return方法打开文件并从中读取文件,然后将文件返回yield给调用者(实际代码在FileStream的using块中。) >

然后,我想知道,是否可以在yield-return方法中使用“ using”或“ try-finally”。因为我的理解是,该方法仅在从中获得值时才运行。例如,使用“ Any()”在第一次收益率返回(或收益率下降)之后完成该方法。

因此,如果函数永远不会结束,什么时候执行finally块?使用这样的结构是否安全?

[我刚刚看了一个YouTube视频,在该视频中,导师使用了yield return方法打开一个文件并从中读取文件,然后将文件返回yield给调用者(实际代码位于...周围的using块中。] >

c# using yield-return
1个回答
0
投票

我刚刚编写了一些测试代码,似乎每次都在适当的时候调用析构函数。

struct Test : IDisposable
{
    public void Dispose() => Console.WriteLine("Destructor called");
}

static IEnumerable<int> InfiniteInts()
{
    Console.WriteLine("Constructor Called");
    using(var test = new Test()) {
        int i = 0;
        while(true)
            yield return ++i;
    }
}

static void Main(string[] args)
{
    var seq = InfiniteInts();
    Console.WriteLine("Call Any()");
    bool b = seq.Any();
    Console.WriteLine("Call Take().ToArray()");
    int[] someInts = seq.Take(20).ToArray();

    Console.WriteLine("foreach loop");
    foreach(int i in seq)
    {
        if(i > 20) break;
    }

    Console.WriteLine("do it manually: while loop");
    var enumerator = seq.GetEnumerator();
    while(enumerator.MoveNext())
    {
         int i = enumerator.Current;
         if(i > 20) break;
    }
    Console.WriteLine("No destructor call has happened!");

    enumerator.Dispose();
    Console.WriteLine("Now destructor has beend called");

    Console.WriteLine("End of Block");
}
© www.soinside.com 2019 - 2024. All rights reserved.