| 
 | 
 
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册  
 
x
 
当使用基类引用访问派生类对象时,得到的是基类的成员,虚方法可以使基类的引用访问“升至”派生类内。 
使用基类引用调用派生类的方法,需要满足下面的条件 
        派生类的方法和基类的方法有相同的签名和返回类型. 
        基类的方法使用virtual标注. 
        派生类的方法使用override标注. 
 
 
/*     
    class MyBaseClass    基类 
    { 
    virtual public void Print() 
    } 
    class MyDerivdeClass:MyBaseClass   派生类 
    { 
    override public void Print() 
    } 
*/ 
 
namespace 虚方法和覆写方法实例 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            MyDerivedClass derived= new MyDerivedClass(); 
            MyBaseClass mybc =derived;          //转化为基类 
            derived.Print(); 
            mybc.Print(); 
            Console.ReadKey(); 
        } 
    }   
    class MyBaseClass          //基类 
    { 
        virtual public void Print()  // 虚方法 
        { 
            Console.WriteLine("This is the base class."); 
        } 
    } 
    class MyDerivedClass : MyBaseClass      //派生类 
    { 
        override public void Print()        //覆写方法 
        { 
            Console.WriteLine("This is the derived class."); 
        } 
    } 
} 
 
输出结果: 
 
This is the derived class. 
 
This is the derived class. |   
 
 
 
 |