foreach 和in的用法
来源:互联网 发布:java贪吃蛇源代码下载 编辑:程序博客网 时间:2024/05/21 21:48
https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/foreach-in
foreach
语句针对实现 System.Collections.IEnumerable 或 System.Collections.Generic.IEnumerable<T> 接口的数组或集合中的每个元素重复一组嵌入语句。 foreach
语句用于循环访问集合以获取所需信息,但不用于添加或删除源集合中的项,以避免不可预知的副作用。 如果需要添加或删除源集合中的项,请使用 for 循环。
为数组或集合中的每个元素继续执行嵌入的语句。 为集合中的所有元素完成迭代后,控制将传递给 foreach
块之后的下一语句。
在 foreach
块中的任何点上,可以使用中断关键字中断该循环,或者可以使用继续关键字单步执行到循环中的下一次迭代。
foreach
循环还可以通过 goto、return 或 throw 语句退出。
有关 foreach
关键字和代码示例的详细信息,请参阅下列主题:
对数组使用 foreach
如何:使用 foreach 访问集合类
示例
下面的代码演示了三个示例:
显示整数数组内容的典型
foreach
循环执行相同操作的 for 循环
维护数组中元素数计数的
foreach
循环
C#
class ForEachTest{ static void Main(string[] args) { int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 }; foreach (int element in fibarray) { System.Console.WriteLine(element); } System.Console.WriteLine(); // Compare the previous loop to a similar for loop. for (int i = 0; i < fibarray.Length; i++) { System.Console.WriteLine(fibarray[i]); } System.Console.WriteLine(); // You can maintain a count of the elements in the collection. int count = 0; foreach (int element in fibarray) { count += 1; System.Console.WriteLine("Element #{0}: {1}", count, element); } System.Console.WriteLine("Number of elements in the array: {0}", count); } // Output: // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13 // 0 // 1 // 1 // 2 // 3 // 5 // 8 // 13 // Element #1: 0 // Element #2: 1 // Element #3: 1 // Element #4: 2 // Element #5: 3 // Element #6: 5 // Element #7: 8 // Element #8: 13 // Number of elements in the array: 8}
阅读全文
0 0
- foreach 和in的用法
- foreach和for in each 的区别
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- Qt foreach 和 QTextCodec类的用法
- for,foreach,iterator的用法和区别
- java中for和foreach的用法
- javascript中filter和forEach的用法
- PHP中foreach的用法和实例
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- forEach和$.each()以及$().each()的用法
- array.foreach() 和 array.map() 的用法
- $.each()和$().each(),以及 forEach ()的用法
- $.each(){} 和<c:forEach>的用法
- smarty中foreach和section的用法
- c# 事件 +=和-=有什么区别。
- yii2.0 的安装
- leetcode Reverse Integer 反转整数
- HDU 4080 字符串哈希+二分
- 文献阅读之Attention-based Crowd Video Classification
- foreach 和in的用法
- Python笔记--散点
- C/C++编码规范
- GET和POST提交方法的区别
- bootstraps如何用在前端页面
- java.lang.NoSuchMethodError:javax.persistence.Table.indexs()[Ljavax/persistence/Index;
- Android开发技术学习之popupwindow的弹窗实现
- Redis 哈希(Hash)
- 【CUGBACM15级BC第9场 A】hdu 4993 Revenge of ex-Euclid