C#父类引用指向子类

来源:互联网 发布:郑州it外包公司 编辑:程序博客网 时间:2024/04/28 02:51

    今天研究了一下 C#中有关父类引用指向子类的问题。所谓“父类引用指向子类”是指声明为父类对象,但实例化创建子类对象。举例说明父类Teacher、子类Professor,声明和实例化:Teacher liming = new Professor (); 将liming声明为教师类,但实例化成教授。先看一段代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication3{    class A    {        public virtual void print()        {            Console.WriteLine ( "A::print()" );         }    }    class B : A    {        public override  void print()        {            Console.WriteLine("B::print()");        }    }        class C :  B     {        public void print(A a)        {            a.print();        }        public override void print()        {            Console.WriteLine("C::print()");        }        static void Main(string[] args)        {            A a = new A ();             A pa = new A ();            A pb = new B ();             A pc = new C ();            B b = new B ();            C c = new C ();            a.print ();            b.print();            c.print ();            pa.print();            pb.print();            pc.print();            c.print(a);            c.print(b);            c.print(c);            String str1 = pa.GetType().ToString();            String str2 = pb.GetType().ToString();            String str3 = pc.GetType().ToString();            Console.WriteLine(str1);            Console.WriteLine(str2);            Console.WriteLine(str3);            Console.ReadKey();                    }    }}

 输出结果如下:

 


 

原创粉丝点击