Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Duyệt mảng kích thước không xác định trong C#

Mảng không khai báo size trước:

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

Dùng Length property trong for loop:

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

Ví dụ

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]);
    }
}

Kết quả

Length: 5
5
7
2
4
1

Best practice: Luôn dùng Length (hoặc Count cho List) thay vì hardcode size. Foreach an toàn hơn nếu không cần index.