第四部分 方法3---------------

   对Employee.CalculatePay方法的调用是问题的原因。我们需要的是晚绑定。晚绑定(Latebinging)意味着编译器到运行时才选择要执行的方法。为了迫使编译器调用向上类型转换得到的对象的方法的正确版本。我们使用了两个关键字:virtual 和override.必须在基类方法中使用virtual 关键字,在方法的派生类实现中使用override 关键字。下面是实现多态的晚绑定的多台性:
class Employee
 {
       public string name;
       public Employee(string name)
              {
                 this.name=name;
              }
       public virtual void CalculatePay()
           {
                Console.WriteLine("Employee.CalculatePay called for {0}",name);
           }
  }
class ContractEmployee:Employee
         {
             public ContractEmployee(string name):base(name)
              {}
             public override void CalculatePay()
               {
                 Console.WriteLine("ContractEmployee.CalculatePay called for {0}",name);
               }
         }
class SalariedEmployee:Employee
    {
         public SalariedEmployee(string name):base(name)
          {}
         public override void CalculatePay()
          {
                Console.WriteLine("SalariedEmployee.CalculatePay called for {0}",name);
          }
    }
class TestPolymorphic
    {
        protected Employee[] employees;
        public void LoadEmployees()
          {
            //Simulating loading from a database.
              employees=new Employee[2];
              employees[0]=new ContractEmployee("Adam Barr");
              employees[1]=new SalariedEmployee("Max Benson");
          }
     }
       public void DoPayroll()
         {
             for(int i=0;i<employees.GetLength(0);i++)
               {
                 employees[i].CalculatePay();
               }
         }
     static void Main(string[] args)
         {
              TestPolymorphic t=new TestPolymorphic();
              t.LoadEmployees();
              t.DoPayroll();
          }
      }
 

你可能感兴趣的:(第四部分 方法3---------------)