Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET循环完整性101_C#_Loops_Ienumerable_Integrity - Fatal编程技术网

C# .NET循环完整性101

C# .NET循环完整性101,c#,loops,ienumerable,integrity,C#,Loops,Ienumerable,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 n

我一直对这件事感到困惑。考虑下面的循环:

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.  
int[]list=newint[]{1,2,3};
对于(inti=0;i
  • 上面的[列表]是硬编码的。如果在循环进行迭代时从外部更改了列表,会发生什么情况
  • 如果[list]是只读属性,例如
    intlist{get{return(newint[]{1,2,3});}}
    ,该怎么办?这会打乱循环吗。如果不是,它会在每次迭代中创建一个新实例吗
井:

  • for
    循环在每次迭代中检查
    列表的长度;实际上,您无法访问循环中的
    list
    ,因此内容是不可逆的
  • foreach
    循环仅使用
    list
    获取迭代器;将其更改为引用不同的列表不会有任何区别,但如果您在结构上修改了列表本身(例如,通过添加值,如果这实际上是一个
    列表而不是
    int[]
    ),则会使迭代器无效
  • 您编写的第三个示例将永远持续下去,除非清除列表,因为它每次都会得到一个新的迭代器。如果您想要更合理的解释,请发布更合理的代码

从根本上讲,您需要理解数组内容与更改变量所指对象之间的区别,然后给我们一个非常具体的情况进行解释。一般来说,
foreach
循环在获取迭代器时只直接接触源表达式一次,而
for
循环没有魔力,访问频率仅取决于代码,每次迭代都会执行
for
循环的条件和“步骤”部分,因此,如果在这些部分中引用变量,您将看到任何更改…

另一点是,对于数组,
Length
属性是不可变的。如果对数组调用
Length
,并获得某个值,则该数组今后所有对
Length
的调用都保证返回相同的值。当然,如果有一个数组类型的实例变量,并且该实例变量被更改为指向另一个数组,那么该数组的长度可能与前面的数组不同。