每次迭代都会评估for循环中的条件吗?

Joa*_*nge 27 .net c# loops

当你做的事情:

for (int i = 0; i < collection.Count; ++i )
Run Code Online (Sandbox Code Playgroud)

是每次迭代都调用collection.Count吗?

如果Count属性动态获取调用计数,结果会改变吗?

Jar*_*Par 26

是计数将在每次通过时进行评估.原因是在执行循环期间可以修改集合.给定循环结构,变量i应该在迭代期间表示集合中的有效索引.如果没有在每个循环上进行检查,那么这是不可证实的.示例案例

for ( int i = 0; i < collection.Count; i++ ) {
  collection.Clear();
}
Run Code Online (Sandbox Code Playgroud)

此规则的一个例外是循环遍历约束为Length的数组.

for ( int i = 0; i < someArray.Length; i++ ) {
  // Code
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,CLR JIT将特殊情况下这种类型的循环,因为数组的长度不能改变.在这些情况下,边界检查只会发生一次.

参考:http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx


Jef*_*tin 13

计数将在每次通过时进行评估.如果你继续添加到集合中并且迭代器从未赶上,那么你将拥有无限循环.

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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这最终将导致内存不足异常.