使用虚方法只有单实例生成的优势吗?

use*_*176 5 c# oop virtual

我了解到虚方法的使用为方法/函数提供了默认行为.我的查询是,当我们可以在派生类中使用"new"实现同名方法(如在基类中)并且可以分别通过对象调用它时,然后使用虚方法.例如;

class A
{
      public void F()
      {
         //default behavior
      }

      public virtual void G()
      {
         //default behavior
      }
}

class B:A
{
    new public void F()
     {
       //new behavior from that of class A
     }
    public override void G()
     {
      //new behavior from that of class A
     }
}

class Test
{
   public static void Main(string[] args)
     {
       //For calling A's method use same compile time and run time object
       A obj1 = new A();

       //For calling B's method use compile time object of A and run time of B
       A obj2 = new B();

       obj1.F(); //O/P is A's method result
       obj2.F(); //O/P is A's method result
       obj1.G(); //O/P is A's method result
       obj2.G(); //O/P is B's method result
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我们可以通过使用相同的编译时对象和类A和B的运行时对象来提供默认行为以及派生行为时,为什么需要类A中的虚拟G():

A obj1 = new A(); //for calling A's methods
B obj2 = new B(); //for calling B's methods
A obj3 = new B(); //for having default behavior of class A using B's run time object.
Run Code Online (Sandbox Code Playgroud)

我获取的只是在虚拟的情况下,我们不需要再创建一个具有相同编译和运行时类型的对象.它可以通过单个对象来实现,该对象是类型A的编译时间和类型B的运行时间.

Jon*_*eet 6

我的问题是,当我们通过使用相同的编译时间和运行时对象以及使用A的编译时对象和B的运行时间来提供默认行为时,为什么需要A类中的虚拟G().

因为那时你只能使用已经知道的代码B.多态性的一半是允许您编写不关心它实际使用的子类的代码.

例如,我可以写复制一个流的内容的方法到另一个使用Stream.ReadStream.Write正因为他们是虚拟的或抽象方法.传入哪些实现并不重要.

你应该很少使用它new作为方法修饰符 - 如果你真的想为非虚方法提供不同的行为,那么如果你创建一个完全不同的方法名称会更清楚,所以阅读代码的任何人都明白这是一个非常独立的方法来自基类中声明的那个.