使用C#中的“新”修饰符修饰符

2023-09-03 15:50:44 作者:情話能暖人卻不暖心

我读了修改器隐藏基类的方法。

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

using System;

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

class B : A
{
    public new void Y()
    {
        // This method HIDES A.Y.
        // It is only called through the B type reference.
        Console.WriteLine("B.Y");
    }
}

class Program
{
    static void Main()
    {
        A ref1 = new A(); // Different new
        A ref2 = new B(); // Polymorpishm
        B ref3 = new B();

        ref1.Y();
        ref2.Y(); //Produces A.Y line #xx
        ref3.Y();
    }
}

为什么 ref2.Y(); 制作 AY 作为输出

这是简单的多态性,基类对象指向派生类,所以应该叫派生类的功能。其实我的Java暨C#codeR;这些概念只是猛然一惊我的脑海里。

This is simple polymorphism, the base class object pointing towards derived class, so it should call the derived class function. I am actually Java cum C# coder; these concepts just boggled my mind.

当我们说隐藏基类的功能,这意味着在的基础的类的功能不能所谓的,这就是隐藏的意思,据我所知。

When we say new hides the base class function, that means the base class function can't be called, that's what hides mean as far as I know.

REF

推荐答案

在C#中,方法不是虚拟的默认(Java不同)。因此, ref2.Y()方法的调用是不是多态。

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

要在多态性中获益,您应该标记 AY()方法虚拟 BY()方法覆盖

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