循环遍历函数结果时,foreach 是如何工作的? [英] How does foreach work when looping through function results?

查看:33
本文介绍了循环遍历函数结果时,foreach 是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码:

foreach(string str in someObj.GetMyStrings())
{
    // do some stuff
}

会在循环的每次迭代中调用 someObj.GetMyStrings() 吗?改为执行以下操作会更好吗:

Will someObj.GetMyStrings() be called on every iteration of the loop? Would it be better to do the following instead:

List<string> myStrings = someObj.GetMyStrings();
foreach(string str in myStrings)
{
    // do some stuff
}

?

推荐答案

该函数只调用一次,返回一个 IEnumerator;之后,MoveNext() 方法和 Current 属性用于遍历结果:

The function's only called once, to return an IEnumerator<T>; after that, the MoveNext() method and the Current property are used to iterate through the results:

foreach (Foo f in GetFoos())
{
    // Do stuff
}

有点等价于:

using (IEnumerator<Foo> iterator = GetFoos().GetEnumerator())
{
    while (iterator.MoveNext())
    {
        Foo f = iterator.Current;
        // Do stuff
    }
}

请注意,迭代器是在最后处理的——这对于从迭代器块中处理资源尤为重要,例如:

Note that the iterator is disposed at the end - this is particularly important for disposing resources from iterator blocks, e.g.:

public IEnumerable<string> GetLines(string file)
{
    using (TextReader reader = File.OpenText(file))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

在上面的代码中,您确实希望在完成迭代时关闭文件,并且编译器巧妙地实现了 IDisposable 以使其工作.

In the above code, you really want the file to be closed when you finish iterating, and the compiler implements IDisposable cunningly to make that work.

这篇关于循环遍历函数结果时,foreach 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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