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

Mảng động (Dynamic Arrays) trong C#

Dynamic arrays là mảng có thể mở rộng, có lợi thế hơn static arrays vì kích thước mảng cố định.

Để tạo mảng động trong C#, dùng collection ArrayList. Nó đại diện cho tập hợp có thứ tự của object có thể index riêng lẻ. Cho phép cấp phát bộ nhớ động, thêm, tìm kiếm, sắp xếp items.

Ví dụ tạo mảng động:

Ví dụ

using System; 
using System.Collections; 
namespace Demo { 
    class Program { 
        static void Main(string[] args) { 
            ArrayList al = new ArrayList(); 
            al.Add(577); 
            al.Add(286); 
            Console.WriteLine("Count: {0}", al.Count); 
            Console.Write("List: "); 
            foreach (int i in al) { 
                Console.Write(i + " "); 
            } 
            Console.WriteLine(); 
            Console.ReadKey(); 
        } 
    } 
}

Kết quả

Count: 2
List: 577 286