委托示例一则

委托派生自基类System.MulticastDelegate,System.MulticastDelegate又派生自System.Delegate,因此使用委托跟使用类有点类似。
使用一个类分为两步骤:1)定义类;2)实例化类的对象(静态类除外)。
同样,使用委托也一样,先定义,后使用。
定义委托,就是告诉编译器,这种类型的委托代表了哪种类型的方法,然后就可以创建委托的一个或多个实例。
定义委托的语法为:
delegate string TestDelegate();
从上面的定义可以看出,委托的安全性非常高,因为它包含了完整的方法签名和返回类型的全部细节。
定义完委托后,就可以创建一个实例,创建完委托的实例后,该实例依旧称作委托,这点跟类和对象还是有区别的。
int x = 5502;
TestDelegate testDel = new TestDelegate(x.ToString);
C#中,委托总是包含带一个参数的构造函数,这个参数即委托引用的方法。
上面的定义等价于:
TestDelegate testDel = x.ToString;
下面用一个例子来看看委托的用法:
假设我们需要比较两个对象的大小,如果不是基本类型,我们很难直接比较。
这是,我们就可以在创建类的时候,提供比较大小的方法,然后将该方法作为参数传递给比较函数,即利用委托。
首先,定义比较的方法Sort:
namespace TianAutoMobile.Test
{
    public class BubbleSorter
    {
        public delegate bool ComparisonDel<T>(T x,T y);
        static public void Sort<T>(T[] sortArray, ComparisonDel<T> comparison)
        {
            for (int i = 0; i < sortArray.Length; i++)
            {
                for (int j = i + 1; j < sortArray.Length; j++)
                {
                    if (comparison(sortArray[j], sortArray[i]))
                    {
                        T temp = sortArray[i];
                        sortArray[i] = sortArray[j];
                        sortArray[j] = temp;
                    }
                }
            }
        }
    }
}

定义一个类,并在类里面实现一个比较类大小的方法:

namespace TianAutoMobile.Test
{
    public 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);
        }

        public static bool CompareSalary(Employee x, Employee y)
        {
            return x.salary < y.salary;
        }
    }
}
 
创建一个测试页面
using System;

namespace TianAutoMobile.Test
{
    public partial class TestPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Employee[] employees = { 
                                   new Employee("Terry chen",5000),
                                   new Employee("Tian xiao",5500),
                                   new Employee("Yu chen",4300),
                                   new Employee("Test",5100)
                                   };
            BubbleSorter.Sort<Employee>(employees,Employee.CompareSalary);

            string employeeList = string.Empty ;
            foreach (var employee in employees)
            {
                employeeList += employee.ToString() + "<br/>";
            }

            allEmployeeList.Text = employeeList;
        }
    }
}
原文地址:https://www.cnblogs.com/tian2010/p/2113259.html