简体   繁体   English

在C#foreach循环中检索到多少次对象列表?

[英]How many times is the list of objects retrieved in a C# foreach loop?

I typically try to store the array/collection as a local variable before running a foreach loop: as opposed to calling the Get function inside of foreach. 我通常尝试在运行foreach循环之前将数组/集合存储为局部变量:与在foreach内部调用Get函数相反。 This is because I assume that it will have to fetch that array on each iteration of the loop, and I would rather it only have to get the array/collection one time. 这是因为我假设它必须在循环的每次迭代中获取该数组,而我宁愿它只需要一次获取该数组/集合。 I'm having trouble finding documentation to support my theory, so I wanted to ask the gurus. 我在寻找文档来支持我的理论时遇到了麻烦,所以我想问问大师。

//Assume that FindStringsContaining() is a CPU
//intensive operation. Does it run only once?
foreach(string data in FindStringsContaining("Data"))
{
    //use the data
}

It will always run exactly once . 它将始终只运行一次

Foreach operates on an IEnumerable , and simply iterates over the collection; Foreach在IEnumerable上运行,并且仅对集合进行迭代; executing the code inside the loop for each item it finds. 为找到的每个项目在循环内执行代码。

Note that modifying the collection during enumeration (which would potentially require a re-enumeration) is explicitly not allowed (an InvalidOperationException will be thrown). 请注意,明确不允许在枚举过程中修改集合(这可能需要重新枚举)(将抛出InvalidOperationException )。

The method call would only happen once. 该方法调用只会发生一次。 It then returns an IEnumerable<string> which is iterating over in a streaming fashion (calling the MoveNext method while items remain in the collection or a break isn't hit). 然后,它返回一个IEnumerable<string> ,它以流方式进行迭代(在项保留在集合中或未命中中断时调用MoveNext方法)。

It is called once. 它被称为一次。 A quick way to verify this is to place a breakpoint inside your FindStringsContaining() method, and you can see it is only hit once. 验证此问题的一种快速方法是将一个断点放置在FindStringsContaining()方法内,您可以看到它仅被命中一次。

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

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