zoukankan      html  css  js  c++  java
  • foreach循环之不能

    foreach循环大部分情况下是和for循环的功能是等同的,但是有其中的两种情况是无法替代for循环的。 今天我来介绍一下这两种情况,第一种,用我的话来说就是:“我们要修改循环项的值的时候,我们不能用foreach循环。” 比如 int[] nArray = new int[10]; ArrayList arrInt = new ArrayList(); arrInt.AddRange(nArray); foreach (int i in nArray) { arrInt.Add(i); } foreach (int i in arrInt) { i++;//编译都会不通过,此时报错误: Cannot assign to 'i' because it is a 'foreach iteration vaiable } 第二种:删除其中的项时不能使用foreach循环, int[] nArray = new int[10]; ArrayList arrInt = new ArrayList(); arrInt.AddRange(nArray); foreach (int i in nArray) { arrInt.Add(i); } foreach (int i in arrInt) { arrInt.Remove(i);//运行是报错:Collection was modified; enumeration operation may not execute. } 遇到上面的两种情况的时候我们只能选择使用其他循环替代,否则无法完成我们的功能。其他情况的时候我们要使用foreach循环,书写简单,以及效率也是最高。
  • 相关阅读:
    第三章 Python基础——文件操作&函数
    第二章python基础续
    第二章Python基础
    四、蒙卦
    三、屯卦
    二、坤卦
    一、乾卦
    1.听力
    Mac搭建github Page的Hexo免费个人博客
    2.4线性表的顺序表示和实现
  • 原文地址:https://www.cnblogs.com/vsdot/p/3263268.html
Copyright © 2011-2022 走看看