[英]Is the condition in a for loop evaluated each iteration?
当您执行以下操作时:
for (int i = 0; i < collection.Count; ++i )
每次迭代都会调用collection.Count吗?
如果 Count 属性在调用时动态获取计数,结果会改变吗?
Yes Count 将在每一次通过时进行评估。 原因是在循环执行期间可能会修改集合。 给定循环结构,变量 i 应该表示迭代期间集合中的有效索引。 如果没有在每个循环上都进行检查,那么这不能证明是正确的。 示例案例
for ( int i = 0; i < collection.Count; i++ ) {
collection.Clear();
}
此规则的一个例外是循环遍历约束为长度的数组。
for ( int i = 0; i < someArray.Length; i++ ) {
// Code
}
在某些情况下,CLR JIT 将特例这种类型的循环,因为数组的长度不能改变。 在这些情况下,边界检查只会发生一次。
参考: http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx
每次通过都会评估计数。 如果您继续添加到集合中并且迭代器从未赶上,您将有一个无限循环。
class Program
{
static void Main(string[] args)
{
List<int> intCollection = new List<int>();
for(int i=-1;i < intCollection.Count;i++)
{
intCollection.Add(i + 1);
}
}
}
这最终将退出 memory 异常。
是的,从 i 初始化后的第一次迭代到检查失败并退出 for 循环的最后一次迭代,每次调用都会检查计数。 如果需要,您可以修改 collections 计数,但要意识到您可能会陷入无限循环。
旁注,这不是为 VB 中的每个交互检查。
与 C# 不同,VB 缓存了集合的结果.Count。
编辑:
C# for 循环的文字 VB 版本是:
Dim i = 0
Do While i < collection.Count
'code goes here
i+=1
Loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.