继承有两个功能强大的方面,其一是代码复用,另一方面更为强大,这就是多态行(polymorphism)。多态是指可以使用一种类型的多种形式,而无需考虑细节。当电话运营商向某个电话发送一个铃声信号时,它并不知道电话线的另一头是什么类型的电话,也许是老式手摇电话,要自己生电响铃,也许是可以演奏数字音乐的电子电话。电话运营商只知道“某类型”电话,它希望这种类型实例都知道如何响铃。当电话运行商让电话响铃时,它只要求电话能够正确响铃。电话公司对电话的这种方式就是多态性的体现。

例如,一个表单想保存它所管理的所有Control实例的集合,这样在表单打开时,可以让自己所有的Control自我绘制。对于此操作,表单并不知道哪个元素是列表框,哪些是按钮,它只需要把集合遍历一次,让它们自己画就行了。简而言之,表单多态性处理Control对象。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace polymorphism

{

    public class Control

    {

        protected int top;

        protected int left;

 

        //构造方法有两个×××参数

        //以确定控制台的位置

        public Control(int top, int left)

        {

            this.top = top;

            this.left = left;

        }

 

        //模拟描绘窗口

        public virtual void DrawWindow()

        {

            Console.WriteLine("Control: Drawing Control at {0},{1}", top, left);

        }

    }

 

    //ListBox派生于Control

    public class ListBox : Control

    {

        private string listBoxContents; //新的成员变量

 

        //构造方法添加一个参数

        public ListBox(int top, int left, string contents)

            : base(top, left)//调用基类构造方法

        {

            listBoxContents = contents;

        }

        

        //重定义版本(注意关键字),因为在派生方法中我们改变了行为

        public override void DrawWindow()

        {

            base.DrawWindow(); //调用基方法

            Console.WriteLine("Writing string to the listbox:{0}", listBoxContents);

        }

    }

 

    //Button派生于Control

    public class Button : Control

    {

        public Button(int top, int left)

            : base(top, left)

        { 

            

        }

 

        //重定义版本(注意关键字),因为在派生方法中我们改变了行为

        public override void DrawWindow()

        {

            Console.WriteLine("Darwing a button at {0},{1}", top, left);

        }

    }

 

    public class Tester

    {

        public static void Main()

        {

            Control win = new Control(1, 2);

            ListBox lb = new ListBox(3, 4, "stand alone list");

            Button b = new Button(5, 6);

            win.DrawWindow();

            lb.DrawWindow();

            b.DrawWindow();

 

            Control[] winArray = new Control[3];

            winArray[0] = new Control(1, 2);

            winArray[1] = new ListBox(3, 4, "ListBox in Array");

            winArray[2] = new Button(5, 6);

 

            for (int i = 0; i < 3; i++)

            {

                winArray[i].DrawWindow();

            }

        }

    }

}

 

//输出为:

 

//Control: Drawing Control at 1,2

//Control: Drawing Control at 3,4

//Writing string to the listbox:stand alone list

//Darwing a button at 5,6

 

//Control: Drawing Control at 1,2

//Control: Drawing Control at 3,4

//Writing string to the listbox:ListBox in Array

//Darwing a button at 5,6

编译器现在知道,要按多态性原则处理对象,使用重新定义的方法。编译器负责跟踪对象的真实类型,以及处理“迟绑定”。