Rah*_*han 3 c# ienumerable loops integrity
我一直对这个感到困惑.考虑以下循环:
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.
Run Code Online (Sandbox Code Playgroud)
int List{get{return(new int [] {1,2,3});}}怎么办?这会扰乱循环吗?如果没有,它会在每次迭代中创建一个新实例吗?好:
for针对循环检查list.Length在每次迭代; 你实际上并没有list在循环中访问,因此内容将是无关紧要的foreach环路只使用list来获得迭代器; 更改它以引用不同的列表没有区别,但是如果你在结构上修改了列表本身(例如通过添加一个值,如果这实际上是一个List<int>而不是一个int[]),那将使迭代器无效从根本上说,你需要理解数组内容与改变变量引用的对象之间的区别 - 然后给我们一个非常具体的情况来解释.一般来说,一个foreach循环只有一次直接接触源表达式,当它获取迭代器时 - 而for循环中没有魔法,并且它的访问频率只取决于代码 - 条件和"步骤"部分该for循环在每个迭代中执行,因此,如果你指的是变量或者那些部分,你会看到任何改变......