在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
};
//长度
Console.WriteLine("Length:" + arr.Length);
for (int i = 0; i < arr.Length; i++) {
Console.WriteLine(arr[i]);
}
}
}输出结果
Length:5 5 7 2 4 1