在 C# 中退出 Foreach 循环

Haider Ali 2023年10月12日
在 C# 中退出 Foreach 循环

本指南将教我们如何在 C# 中退出 foreach 循环。这是另一种简单的方法,不涉及复杂性。

让我们深入了解本指南并查看此代码的实现。

C# 中退出 foreach 循环

有两种方法可以用来退出 foreach 循环或任何其他循环。退出 foreach 循环与退出任何其他循环相同。

这两种方式都很常见,而且它们也是许多其他语言中最常用的方式。例如,C、C++、Java 等。

我们可以使用 break 方法或 return 方法。这两种方式都可以用来退出 foreach 循环。

看看下面的代码。

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

namespace For_Each_Loop {
  class Program {
    static void Main(string[] args) {
      int[] numbers_arr = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };  // Example Array

      foreach (int i in numbers_arr) {
        System.Console.Write("{0} ", i);
        Console.ReadKey();  // To Stay On Screen
        if (i == 3) {
          break;  // IF You want To break and end the function call
        }
      }

      foreach (int i in numbers_arr) {
        System.Console.Write("{0} ", i);
        Console.ReadKey();  // To Stay On Screen
        if (i == 2) {
          return;  // IF You want To break and end the function call
        }
      }
    }
  }
}

我们在上面的代码中同时使用了 breakreturn。你需要做的就是写 break;返回; 根据你的需要在 foreach 循环内。

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Csharp Loop