Using the 'new' modifier in C#

后端 未结 3 2132
醉话见心
醉话见心 2020-12-11 01:48

I read that the new modifer hides the base class method.

using System;

class A
{
    public void Y()
    {
        Console.WriteLine(\"A.Y\");
         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 02:22

    In C#, methods are not virtual by default (unlike Java). Therefore, ref2.Y() method call is not polymorphic.

    To benefit from the polymorphism, you should mark A.Y() method as virtual, and B.Y() method as override.

    What new modifier does is simply hiding a member that is inherited from a base class. That's what really happens in your Main() method:

    A ref1 = new A();
    A ref2 = new B();
    B ref3 = new B();
    
    ref1.Y(); // A.Y
    ref2.Y(); // A.Y - hidden method called, no polymorphism
    ref3.Y(); // B.Y - new method called
    

提交回复
热议问题