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

619

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

private class AscendingCirculationComparer : IComparer {

int IComparer.Compare(object x, object y) {

// Xử lý các tham chiếu null.

// Null được coi như nhỏ hơn bất cứ giá trị nào khác.

if (x == null && y == null) return 0;

else if (x == null) return -1;

else if (y == null) return 1;

// Trường hợp x và y tham chiếu đến cùng một đối tượng.

if (x == y) return 0;

// Bảo đảm x và y đều là các thể hiện của Newspaper.

Newspaper newspaperX = x as Newspaper;

if (newspaperX == null) {

throw new ArgumentException("Invalid object type", "x");

}

Newspaper newspaperY = y as Newspaper;

if (newspaperY == null) {

throw new ArgumentException("Invalid object type", "y");

}

// So sánh circulation. IComparer quy định rằng:

// trả về một số âm nếu x < y

// trả về zero nếu x = y

// trả về một số dương nếu x > y

// Dễ dàng hiện thực logic này bằng phép tính số nguyên.

return newspaperX.circulation - newspaperY.circulation;

}

}

public Newspaper(string name, int circulation) {