Giới thiệu
Collection<T> (namespace System.Collections.ObjectModel) hỗ trợ indexer để truy cập phần tử theo chỉ mục. Đây là lớp cơ sở lý tưởng cho tập hợp tùy chỉnh.
Ví dụ 1: Lấy phần tử tại chỉ mục
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach (string str in col)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
Console.WriteLine("Element at index 4 = " + col[4]);
}
}
Kết quả
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 4 = Tablet
Ví dụ 2: Cập nhật phần tử tại chỉ mục
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection<string> col = new Collection<string>();
col.Add("Laptop");
col.Add("Desktop");
col.Add("Notebook");
col.Add("Ultrabook");
col.Add("Tablet");
col.Add("Headphone");
col.Add("Speaker");
Console.WriteLine("Elements in Collection...");
foreach (string str in col)
{
Console.WriteLine(str);
}
Console.WriteLine("Element at index 3 = " + col[3]);
col[3] = "SSD";
Console.WriteLine("Element at index 3 (Updated) = " + col[3]);
}
}
Kết quả
Elements in Collection... Laptop Desktop Notebook Ultrabook Tablet Headphone Speaker Element at index 3 = Ultrabook Element at index 3 (Updated) = SSD
Đặc điểm Collection<T>
- Cung cấp các phương thức ảo bảo vệ:
InsertItem,SetItem,RemoveItem,ClearItems - Cho phép ghi đè để thêm logic validation
- Hỗ trợ đầy đủ
IList<T>,ICollection<T>,IEnumerable<T> - Indexer O(1) cho cả get và set
Ví dụ tùy chỉnh (Validation)
public class ValidatedCollection<T> : Collection<T>
{
protected override void SetItem(int index, T item)
{
if (item == null) throw new ArgumentNullException(nameof(item));
base.SetItem(index, item);
}
}