CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 621

621

Chương 16: Các giao diện và mẫu thông dụng

// Tính giá trị trả về bằng cách thực hiện phép so sánh

// trường name (không phân biệt chữ hoa-thường).

// Vì name là chuỗi nên cách dễ nhất là dựa vào khả năng

// so sánh của lớp String (thực hiện phép so sánh chuỗi

// có phân biệt bản địa).

return string.Compare(this.name, other.name, true);

}

}

}

Phương thức

Main

minh họa phép so sánh và khả năng sắp xếp nhờ có hiện thực giao diện

IComparable

IComparer

. Phương thức này sẽ tạo một tập hợp

System.Collections.ArrayList

chứa năm đối tượng

Newspaper

, sau đó sắp xếp

ArrayList

hai

lần bằng phương thức

ArrayList.Sort

. Lần đầu, thao tác

Sort

sử dụng cơ chế so sánh mặc

định của

Newspaper

(thông qua phương thức

IComparable.CompareTo

). Lần sau, thao tác

Sort

sử dụng đối tượng

AscendingCirculationComparer

(thông qua phương thức

IComparer.Compare

).

public static void Main() {

ArrayList newspapers = new ArrayList();

newspapers.Add(new Newspaper("Tuoi Tre", 125780));

newspapers.Add(new Newspaper("Echip", 55230));

newspapers.Add(new Newspaper("Thanh Nien", 235950));

newspapers.Add(new Newspaper("Phu Nu", 88760));

newspapers.Add(new Newspaper("Tiep Thi", 5670));

Console.WriteLine("Unsorted newspaper list:");

foreach (Newspaper n in newspapers) {

Console.WriteLine(n);

}

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Newspaper list sorted by name (default order):");

newspapers.Sort();

foreach (Newspaper n in newspapers) {

Console.WriteLine(n);

}

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.