Những chủ đề tiến bộ trong C#
Delegate – Phần 2
Định nghĩa delegate như sau:
delegate bool CompareOp(object lhs, object rhs);
Và xây dựng phương thức sort() là :
static public void Sort(object [] sortArray, CompareOp gtMethod)
Phn ng dẫn cho phương thức này s nói rõ rng gtmethod phải tham
chiếu đến 1 phương thức static 2 đối s,và trvtrue nếu giá trị ca đối
số thứ 2 là 'lớn hơn' ( nghĩa là năm sau trong mảng) đối số thứ nhất.
mặc dù ta có thể sử dụng delegate ở đây,nhưng cũng có thể giải quyết vn đề
bằng cách sử dụng interface. .NET xây dng 1 interface IComparer cho mục
đích này. tuy nhiên , ta sdụng delegate vì loại vn đề này t thường
khuynh hướng dùng delegate.
Sau đây lớp bublesorter :
class BubbleSorter
{
static public void Sort(object [] sortArray, CompareOp gtMethod)
{
for (int i=0 ; i<sortArray.Length ; i++)
{
for (int j=i+1 ; j<sortArray.Length ; j++)
{
if (gtMethod(sortArray[j], sortArray[i]))
{
object temp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = temp;
}
}
}
}
}
Để dùng lớp này ta cn định nghĩa 1 slớp khác mà thdùng thiết lập
mảng cn sắp xếp.ví d, công ty điện thoại có danh sách tên khách hàng,
mun sắp danh sách theo lương.mỗi nhân viên trình y bi thể hiện của
một lớp , Employee:
class Employee
{
private string name;
private decimal salary;
public Employee(string name, decimal salary)
{
this.name = name;
this.salary = salary;
}
public override string ToString()
{
return string.Format(name + ", {0:C}", salary);
}
public static bool RhsIsGreater(object lhs, object rhs)
{
Employee empLhs = (Employee) lhs;
Employee empRhs = (Employee) rhs;
return (empRhs.salary > empLhs.salary) ? true : false;
}
}
Lưu ý để phù hợp với dấu ấn của delegate CompareOp, chúng ta phải định
nghĩa RhsIsGreater trong lớp này lấy 2 đối tượng để tham khảo,hơn tham
khảo employee như thông số.điều này có nghĩa là ta phải ép kiểu những
thông số vào trong tham khảo employee để thực thi việc so sánh.
Bây giờ ta viết mã yêu cu sắp xếp :
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
delegate bool CompareOp(object lhs, object rhs);
class MainEntryPoint
{
static void Main()
{
Employee [] employees =
{
new Employee("Karli Watson", 20000),
new Employee("Bill Gates", 10000),
new Employee("Simon Robinson", 25000),
new Employee("Mortimer", (decimal)1000000.38),
new Employee("Arabel Jones", 23000),
new Employee("Avon from 'Blake's 7'", 50000)};
CompareOp employeeCompareOp = new
CompareOp(Employee.RhsIsGreater);
BubbleSorter.Sort(employees, employeeCompareOp);
for (int i=0 ; i<employees.Length ; i++)
Console.WriteLine(employees[i].ToString());
}
}
Chạy mã này sthấy employees được sắp xếp theo lương
BubbleSorter
Bill Gates, £10,000.00
Karli Watson, £20,000.00