using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace 虚方法
{
    class C
    {
        public
        virtual
        void method()
        {
            Console.WriteLine("C Method!");
        }
    }    class D : C
    {
        public
        override
        void method()
        {
            //base.method();
            Console.WriteLine("D Method!");
        }
    }
    class DC : C
    {
        public
        new
        void method() //此处隐藏了父类的method方法,使用new关键 字.
        {             //如不不 使用new,编译器会报警告消息,但仍然
            //是隐藏父类访求method()            //base.method();
            Console.WriteLine("dc method!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
                       C cdClass =
            new D();
            cdClass.method();//调用D中的method(),输出(C Method! D Method!);其中C Method!是由D中的base.method()输出.
            Console.WriteLine("=============");       
            //D dcClass = new C();//编译无法通过
            //dcClass.method();
            DC dcClass =
   new DC();
            dcClass.method();//调用DC中的method(),输出(C Method! DC Method!);此处隐藏了父类的方法
            Console.WriteLine("=============");            //说明: 如果用类C修饰DC对象:
            C dcClass2 = new DC();
            dcClass2.method(); //调用C中的method(),输出(C Method!)
            Console.WriteLine("=============");        }
    }
}
 C cdClass =
            new D();调用的是d.method
C dcClass2 = new DC();
            dcClass2.method(); 
                     调用的是c.method
不理解。
求大家指点。。

解决方案 »

  1.   

    new表示重写,如果希望用D则需要override
      

  2.   

     C cdClass =
      new D();调用的是d.method父类引用指向子类对象,如果子类重写了父类的方法,那么调用子类中重写的方法。
    C dcClass2 = new DC();
      dcClass2.method(); 
      调用的是c.method父类引用指向子类对象,如果子类中没有重写父类的方法,那么将调用父类中的方法。
    (子类中用了new,就说明不是重写,该方法只能通过子类自己的引用来调用。)这里就说明了接口和抽象类为什么要求在子类中必须实现所有方法
    就是为了防止接口或抽象类作为父类引用指向子类对象,如果子类不重写的话,那么将调用接口或抽象类中的方法。
    而接口和抽象类中只有方法声明,无法调用,就要出问题了。
      

  3.   

    错了 new 不是重写的。
    1.new 的功能是 创建对象。
    2.new 的功能是 隐藏父类的相同名字的方法。
    override 才是重写,前提一定是 父类 有虚方法和抽象方法(一定存在在抽象类中)
    楼主:
    1.封装;
    2.多台;
    3.继承。你去了解这3个就知道 面向对象 和 面向过程的区别了。
      

  4.   


    我实在不知道该怎么翻译这个new,但我的理解是这个new表示无视父类中同名的方法,或者说断绝关系,改为采用自己定义的方法,重新写一个同名的方法,我不知道这个翻译有什么问题,new表示一个从新开始的意思。而override,你可以查查牛津英英,http://oald8.oxfordlearnersdictionaries.com/dictionary/override
    to use your authority to reject somebody's decision, order, etc.本身表示推翻,覆盖的意思,你去体会一些,其实把override翻译成重写是一件非常非常牵强的事情,尤其是在有了new以后,我觉得extend,扩展甚至inject插入更能表达这个意思。英语可能会更清楚一些
    The new modifier creates a new member with the same name and causes the original member to become hidden. The override modifier extends the implementation for an inherited member.另外想问问你把override翻译成重写,你怎么翻译new,我倒是挺敢兴趣的,总不见得翻译为隐藏吧。