日期:2011-04-25  浏览次数:20545 次

 

在C#中使用一个类时,分两个阶段。首先需要定义这个类,即告诉编译器这个类由什么字段和方法组成。然后(除非只使用静态方法)实例化类的一个对象。使用委托时,也需要经过这两个步骤。首先定义要使用的委托,对于委托,定义它就是告诉编译器这种类型代表了那种类型的方法,然后创建该委托的一个或多个实例。
定义委托是从delegate开始的然而它是如何运作的呢。也许弄个鼠标事件会容易理解一些,这里还是拿出书中的例子来。

using System;

namespace Wrox.ProfCSharp.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());
         Console.ReadLine();
      }
   }

   class Employee // : object
   {
      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;
      }
   }

   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]))
   &nb