C#中foreach命令的使用

https://www.cnblogs.com/jiading/p/9649860.html

在Python中,for循环不仅可以用来做指定次数的循环,还可以利用for i in xxx:来实现元素的遍历,遍历的对象几乎可以是任意格式。而在C++以及C#中,除了普通的for循环之外,也提供了这样的遍历方法,叫foreach。它可以说是一种增强型的for循环。

  实例一

 
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace solve1
 8 {
 9 
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
15             foreach (int i in array)
16                 Console.WriteLine(i);
17         }
18     }
19 }

结果为

1
2
3
4
5
6
7
8
9
请按任意键继续. . .

它实现了对数组元素的遍历,和Python不同的是,遍历之前需要指定元素的类型。

实例二

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace solve1
 8 {
 9 
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             string test = "Hello,world!";
15             foreach (char i in test)
16                 Console.WriteLine(i);
17         }
18     }
19 }

输出结果为:

H
e
l
l
o
,
w
o
r
l
d
!
请按任意键继续. . .

说明foreach循环也可以遍历字符串,元素类型为char。

另外,将上面代码中i的类型由char改为int,结果为:

72
101
108
108
111
44
119
111
114
108
100
33
请按任意键继续. . .

可以看到,输出的结果是字符所对应的ASCII码值,说明这里进行了数据类型的隐式转换。

综上,foreach命令不失为在元素个数不确定的情况下进行遍历的一种更加简洁的方法。

原文地址:https://www.cnblogs.com/SophieWang-cmu/p/12841804.html