C#中foreach命令的使用

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

  实例一

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace solve1
{

    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            foreach (int i in array)
                Console.WriteLine(i);
        }
    }
}

结果为

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

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

  实例二

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace solve1
{

    class Program
    {
        static void Main(string[] args)
        {
            string test = "Hello,world!";
            foreach (char i in test)
                Console.WriteLine(i);
        }
    }
}

输出结果为:

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/jiading/p/9649860.html