在 C# 中使用“新"修饰符 [英] Using the 'new' modifier in C#

查看:42
本文介绍了在 C# 中使用“新"修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到 new 修饰符隐藏了基类方法.

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(); 产生 A.Y 作为输出?

Why does ref2.Y(); produce A.Y as output?

这是简单的多态,基类对象指向派生类,所以应该调用派生类函数.我实际上是 Java 兼 C# 编码器;这些概念让我大吃一惊.

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.

当我们说new隐藏基类函数时,就是说base类函数不能被调用,这就是隐藏的意思据我所知.

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.

参考

推荐答案

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

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

要从多态中受益,您应该将 AY() 方法标记为 virtual,并将 BY() 方法标记为 override.

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

new 修饰符所做的只是隐藏从基类继承的成员.这就是您的 Main() 方法中真正发生的事情:

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

这篇关于在 C# 中使用“新"修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆