C#語言提供的foreach語句是一個for語句循環的捷徑,而且還促進了集合類的更為一致,先來看看它的定義格式:
foreach語句的定義格式為:
foreach(類型 變量 in 集合)
{
子語句;
}
每執行一次內嵌語句,循環變量就依次取集合中的一個元素代入其中,在這里,循環變量是一個只讀型局部變量,如試圖改變其值將會發生編譯錯誤。
foreach語句用于列舉出集合中所有的元素,foreach語句中的表達式由關鍵字in隔開的兩個項組成。in右邊的項是集合名,in左邊的項是變量名,用來存放該集合中的每個元素。
foreach語句的優點一:語句簡潔,效率高。
用一個遍歷數組元素的例子來說明:
先用foreach語句來輸出數組中的元素:
<span style="font-size:18px;"> int[,] ints =new int[2,3]{{1,2,3},{4,5,6}}; foreach (int temp in ints) { Console.WriteLine(temp); } Console.ReadLine();</span>
再用for語句輸出數組中元素:
<span style="font-size:18px;"> int[,] ints =new int[2,3]{{1,2,3},{4,5,6}}; for (int i = 0; i < ints.GetLength(0); i++) { for (int j = 0; j < ints.GetLength(1); j++) { Console.WriteLine(ints[i,j]); } } Console.ReadLine();</span>
這兩種代碼執行的結果是一樣的都是每行一個元素,共6行,元素分別是1 2 3 4 5 6。
在一維數組中還無法體現出foreach語句的簡潔性,高效率性,但是在二維數組,甚至多維數組中體現的更為明顯和方便,所以在C#語言中要用循環語句提倡使用foreach語句。
foreach語句的優點二:避免不必要的因素
在C#語言中使用foreach語句不用考慮數組起始索引是幾,很多人可能從其他語言轉到C#的,那么原先語言的起始索引可能不是1,例如VB或者Delphi語言,那么在C#中使用數組的時候就難免疑問到底使用0開始還是用1開始呢,那么使foreach就可以避免這類問題。
foreach語句的優點三:foreach語句自動完成類型轉換
這種體現可能通過如上的例子看不出任何效果,但是對于ArrayList之類的數據集來說,這種操作就顯得比較突出。
先用foreach語句來實現類型轉換操作:在使用ArrayList類時先要引入using System.Collections;
<span style="font-size:18px;"> int[] a=new int[3]{1,2,3}; ArrayList arrint = new ArrayList(); arrint.AddRange(a); foreach (int temp in arrint) { Console.WriteLine(temp); } Console.ReadLine();</span>
再來使用for語句來實現:需要進行顯式的強制轉換
<span style="font-size:18px;"> int[] a=new int[3]{1,2,3}; ArrayList arrint = new ArrayList(); arrint.AddRange(a); for (int i = 0; i < arrint.Count;i++ ) { int n = (int)arrint[i]; Console.WriteLine(n); } Console.ReadLine();</span>
兩個程序輸出的結果為:每一行一個元素,分別為1,2,3。
foreach語句對于string類更是簡潔:
<span style="font-size:18px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace @foreach { class Program { static void Main(string[] args) { string str = "This is an example of a foreach"; foreach (char i in str) { if (char.IsWhiteSpace(i)) { Console.WriteLine(i);//當i為空格時輸出并換行 } else { Console.Write(i);//當i不為空格時只是輸出 } } Console.ReadLine(); } } }</span>
輸出的結果為:每一行一個單詞,分別為This, is ,an ,example ,of ,a ,foreach。
對于foreach語句的理解,目前也就知道這多了,隨著更深層次的學習,或許會有更好的理解吧。
以上就是本文的全部內容,希望對大家的學習有所幫助。
新聞熱點
疑難解答