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命令不失為在元素個數不確定的情況下進行遍歷的一種更加簡潔的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM