.NET 循环完整性 101
对于这个问题我一直很困惑。考虑以下循环:
int [] list = new int [] { 1, 2, 3 };
for (int i=0; i < list.Length; i++) { }
foreach (int i in list) { }
while (list.GetEnumerator().MoveNext()) { } // Yes, yes you wouldn't call GetEnumerator with the while. Actually never tried that.
- 上面的 [list] 是硬编码的。如果在循环迭代时列表被外部更改,会发生什么?
- 如果 [list] 是只读属性,例如
int List{get{return(new int [] {1,2,3});}}
会怎样?这会扰乱循环吗?如果不是,它会在每次迭代中创建一个新实例吗?
I've always been confused about this one. Consider the following loops:
int [] list = new int [] { 1, 2, 3 };
for (int i=0; i < list.Length; i++) { }
foreach (int i in list) { }
while (list.GetEnumerator().MoveNext()) { } // Yes, yes you wouldn't call GetEnumerator with the while. Actually never tried that.
- The [list] above is hard-coded. If the list was changed externally while the loop was going through iterations, what would happen?
- What if the [list] was a readonly property e.g.
int List{get{return(new int [] {1,2,3});}}
? Would this upset the loop. If not, would it create a new instance in each iteration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧:
for
循环在每次迭代时都会检查list.Length
;您实际上并没有在循环内访问list
,因此内容无关紧要foreach
循环仅使用list
来获取迭代器;将其更改为引用不同的列表不会有任何区别,但如果您在结构上修改了列表本身(例如,通过添加一个值,如果这实际上是一个List
而不是int[]
),这将使迭代器无效从根本上讲,您需要了解数组内容与更改变量引用的对象之间的区别 - 然后给我们一个非常具体的情况解释。不过,一般来说,
foreach
循环在获取迭代器时仅直接接触源表达式一次 - 而for
循环并没有什么魔力,也没有访问它的频率仅取决于代码 -for
循环的条件和“step”部分都会在每次迭代中执行,因此,如果您引用这些部分中任一部分中的变量,您将看到任何改变...Well:
for
loop checks againstlist.Length
on each iteration; you don't actually accesslist
within the loop, so the contents would be irrevelantforeach
loop only useslist
to get the iterator; changing it to refer to a different list would make no difference, but if you modified the list itself structurally (e.g. by adding a value, if this were really aList<int>
instead of anint[]
), that would invalidate the iteratorFundamentally you need to understand the difference between the contents of an array vs changing which object a variable refers to - and then give us a very concrete situation to explain. In general though, a
foreach
loop only directly touches the source expression once, when it fetches the iterator - whereas afor
loop has no magic in it, and how often it's accessed simply depends on the code - both the condition and the "step" part of thefor
loop are executed on each iteration, so if you refer to the variable in either of those parts, you'll see any changes...