本文實例講述了C#中foreach語句使用break暫停遍歷的方法。分享給大家供大家參考。具體分析如下:
下面的代碼演示了在C#中使用foreach時如何通過break語句暫停數據遍歷
using System;public class w3demo { public static void Main() { int sum = 0; int[] nums = new int[10]; // give nums some values for(int i = 0; i < 10; i++) nums[i] = i; // use foreach to display and sum the values foreach(int x in nums) { Console.WriteLine("Value is: " + x); sum += x; if(x == 4) break; // 當x=4時停止遍歷 } Console.WriteLine("Summation of first 5 elements:" + sum); }}
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答