前两天看书的时候看到两个关于委托的实例,今天自己工作的时候也突然想起来其中一些内容可以很好的借鉴,
感觉也很有代表性,就又敲了一遍,也做了些注释和自己的看法,记录如下:
//静态方法二
public static double Square(double value)
{
return value * value;
}
}
/// <summary>
/// 委托的定义
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
delegate double DoubleOp(double x);
class Program
{
static void Main(string[] args)
{
//委托类型的数组,其中实现了MathsOperations类两个静态方法的委托
//由此更能够体现处理委托就像处理一般的类一样
DoubleOp[] operations =
{
MathsOperations.MultiplyByTwo,
MathsOperations.Square
};
//循环委托数组,实现数学计算
for (int i = 0; i < operations.Length; i++)
{
Console.WriteLine("Using operations[{0}]", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
Console.Read();
}
/// <summary>
/// 通过传递得到的委托,来执行MathsOperations类的静态计算方法
/// </summary>
/// <param name="action">一个委托</param>
/// <param name="value">参与数学计算的值</param>
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
//通过使用action()来调用委托的方法
double result = action(value);
Console.WriteLine("Value is {0}, result of operation is {1}", value, result);
}
}
}
//定义一个委托,要注意参数的类型 object
delegate bool Comparison(object x,object y);
// 用来实现为数组排序的公共类
class BubbleSorter
{
/// <summary>
/// 对数组的排序
/// </summary>
/// <param name="sortArray">排序对象数组</param>
/// <param name="comparison">用来实现大小比较的委托的对象</param>
static public void Sort(object[] sortArray, Comparison comparison)
{
for (int i = 0; i < sortArray.Length; i++)
{
for (int j = 0; j < sortArray.Length; j++)
{
//执行委托的方法
if (comparison(sortArray[j], sortArray[i]))
{
object temp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = temp;
}
}
}
}
}
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("{0},{1:C}", name, salary);
}
//用来实现对Employees实例对象的比较,作为参数传递给委托
public static bool CompareSalary(object x, object y)
{
Employee e1 = (Employee)x;
Employee e2 = (Employee)y;
return (e1.salary < e2.salary);
}
}
class Program
{
static void Main(string[] args)
{
//employees类的数组
Employee[] employees =
{
new Employee("Mr.A", 20000),
new Employee("Mr.B", 50000),
new Employee("Mr.C", 25000),
new Employee("Mr.D", (Decimal)19999.99)
};
//将Employee.CompareSalary的函数名作为参数传递给委托对象
//这一句还可以写成:BubbleSorter.Sort(employees, new Comparison(Employee.CompareSalary));
BubbleSorter.Sort(employees, Employee.CompareSalary);
foreach (var emp in employees)
{
Console.WriteLine(emp);
}
Console.Read();
}
}
}