如何在 C# 中高效地迭代大小未知的整数数组

csharpprogrammingserver side programming更新于 2025/5/25 10:22:17

在 C# 中高效地迭代大小未知的整数数组非常简单。让我们看看如何操作。

首先,设置一个数组,但不设置其大小 −

int[] arr = new int[] { 5, 7, 2, 4, 1 };

现在,获取数组的长度,并使用 for 循环迭代数组。 −

for (int i = 0; i< arr.Length; i++) {
   Console.WriteLine(arr[i]);
}

让我们看完整的示例 −

示例

using System;

public class Program {
   public static void Main() {
      int[] arr = new int[] {
         5,
         7,
         2,
         4,
         1
      };

      // Length
      Console.WriteLine("Length:" + arr.Length);

      for (int i = 0; i < arr.Length; i++) {
         Console.WriteLine(arr[i]);
      }
   }
}

输出

Length:5
5
7
2
4
1

相关文章