Giới thiệu
Collection<T> (namespace System.Collections.ObjectModel) là base class cho collection tùy chỉnh. Phương thức GetEnumerator() trả về IEnumerator<T> để duyệt.
Ví dụ 1: Collection với trùng lặp
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection col = new Collection();
col.Add("Andy");
col.Add("Kevin");
col.Add("John");
col.Add("Kevin"); // cho phép trùng
col.Add("Mary");
col.Add("Katie");
col.Add("Barry");
col.Add("Nathan");
col.Add("Mark");
Console.WriteLine("Số phần tử = " + col.Count);
Console.WriteLine("Duyệt qua collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
}
Kết quả
Số phần tử = 9
Duyệt qua collection...
Andy
Kevin
John
Kevin
Mary
Katie
Barry
Nathan
Mark
Ví dụ 2: Collection
using System;
using System.Collections.ObjectModel;
public class Demo
{
public static void Main()
{
Collection col = new Collection();
col.Add(100);
col.Add(200);
col.Add(300);
col.Add(400);
col.Add(500);
Console.WriteLine("Số phần tử = " + col.Count);
Console.WriteLine("Duyệt qua collection...");
var enumerator = col.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
}
Kết quả
Số phần tử = 5
Duyệt qua collection...
100
200
300
400
500
Đặc điểm
Collection<T>implementIList<T>,ICollection<T>,IEnumerable<T>.- Có các phương thức virtual
InsertItem,SetItem,RemoveItem,ClearItemsđể override tùy chỉnh hành vi. - Phù hợp làm base class cho collection có logic validate, notification.