我是靠谱客的博主 酷炫画笔,这篇文章主要介绍C# foreach的用法,现在分享给大家,希望可以做个参考。

 foreach是一种语法糖,用来简化对可枚举元素的遍历代码。而被遍历的类通过实现IEnumerable接口和一个相关的IEnumerator枚举器来实现遍历功能。

在foreach语句中有两个限制,第一不能修改枚举成员,其次不要对集合进行删除操作。也就是如下两种方式都是错误的。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
        // Use "foreach" to loop an arraylist         foreach( int i in arrInt )         {             i++;//Can't be compiled             Debug.WriteLine( i.ToString() );         }           // Use "foreach" to loop an arraylist         foreach( int i in arrInt )         {             arrInt.Remove( i );//It will generate error in run-time             Debug.WriteLine( i.ToString() );         }

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestForeach : MonoBehaviour { void Start() { GoTestForeach(); } private void GoTestForeach() { Debug.Log("start foreach 空数组的遍历"); var array = new List<string>(); //注意区分:空数组是指元素个数为0,数组为空是指数组变量本身为null foreach(var item in array) { //这里数组array变量不为空,只是元素个数为0,在遍历时不会报空。 Debug.Log(item); } //foreach语句中不能修改枚举成员 var array2 = new List<string> { "", "1", "2", "3" }; foreach(var item in array2) { Debug.Log(item); array2.Remove("1"); Debug.Log(item); } } }

 那么对于如上两个操作,可以用for来实现,此外这里多说一句,就是对于一个记录集的多条数据删除问题,也是经常出现问题的地方(论坛上经常问类似的问题),由于在一些记录集中进行删除的时候,在删除操作之后相应的索引也发生了变化,这时候的删除要反过来进行删除,大致形式如下。

复制代码
1
2
3
4
5
6
7
8
9
        // Use "for" to loop an arraylist         for( int i = arrInt.Count - 1; i >=0; i-- )         {             int n = ( int ) arrInt[i];             if( n == 5 )                 arrInt.RemoveAt( i ); // Remove data here             Debug.WriteLine( n.ToString() );         }  

除了这两个地方外,foreach可以基本适用于任何循环
 

IEnumerator , IEnumerable 枚举器接口_Peter_Gao_的博客-CSDN博客
https://blog.csdn.net/hc1104/article/details/8130818

最后

以上就是酷炫画笔最近收集整理的关于C# foreach的用法的全部内容,更多相关C#内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部