实例构造函数疑问

类别:.NET开发 点击:0 评论:0 推荐:

请看例子

using System;

 

namespace _4_5_2

{

   /// <summary>

   /// Class1 的摘要说明。

   /// </summary>

   class TestNotPoly

   {

      /// <summary>

      /// 应用程序的主入口点。

      /// </summary>

      [STAThread]

      static void Main(string[] args)

      {

        TestNotPoly tt=new TestNotPoly();

        tt.LoadEmployees();

        tt.DoPayroll();

      }

      protected  Employee[] employees;

      public  void LoadEmployees()

      {

        employees=new Employee[2];

        employees[0]=new ContactEmployee("masathem");

        employees[1]=new SalariesEmployee("anubis");

      }

      public  void DoPayroll()

      {

        for(int i=0;i<employees.GetLength(0);i++)

        {

           employees[i].CaculatePay();

        }

      }

   }

   class Employee

   {

      public string name;

      public Employee(string name)

      {

        this.name=name;

      }

      public void CaculatePay()

      {

        Console.WriteLine("[Employee].CaculatePay() name :{0}",name);

      }

   }

   class SalariesEmployee:Employee

   {

      public SalariesEmployee(string name):base(name){}

      public new void CaculatePay()

      {

        Console.WriteLine("[SalariesEmployee].CaculatePay() name :{0}",name);

      }

   }

   class ContactEmployee:Employee

   {

      public ContactEmployee(string name):base(name){}

      public new void CaculatePay()

      {

        Console.WriteLine("[ContactEmployee].CaculatePay() name :{0}",name);

      }

   }

}

 


SalariesEmployee 继承自Employe

使用派生类实例化基类对象

employees[0]=new ContactEmployee("masathem");
employees[1]=new SalariesEmployee("anubis");

但employees[]是Employee对象,但是通过“重载”??却能向下调用派生类的方法?employees[]到底是不是基类对象?

看IL解释

.method public hidebysig instance void  LoadEmployees() cil managed

{

  // 代码大小       49 (0x31)

  .maxstack  4

  IL_0000:  ldarg.0

  IL_0001:  ldc.i4.2

  IL_0002:  newarr     _4_5_2.Employee

  IL_0007:  stfld      class _4_5_2.Employee[] _4_5_2.TestNotPoly::employees

  IL_000c:  ldarg.0

  IL_000d:  ldfld      class _4_5_2.Employee[] _4_5_2.TestNotPoly::employees

  IL_0012:  ldc.i4.0

  IL_0013:  ldstr      "masathem"

  IL_0018:  newobj     instance void _4_5_2.ContactEmployee::.ctor(string)

  IL_001d:  stelem.ref

  IL_001e:  ldarg.0

  IL_001f:  ldfld      class _4_5_2.Employee[] _4_5_2.TestNotPoly::employees

  IL_0024:  ldc.i4.1

  IL_0025:  ldstr      "anubis"

  IL_002a:  newobj     instance void _4_5_2.SalariesEmployee::.ctor(string)

  IL_002f:  stelem.ref

  IL_0030:  ret

} // end of method TestNotPoly::LoadEmployees

 

荧光笔标记的是派生类的实例构造函数,得到的类为什么能调用此派生类的方法?虽然调用的是派生类来实例化的,但是它终久是基类?基类能调用派生类的方法?

本文地址:http://com.8s8s.com/it/it43480.htm