在 C# 中使用“新"修饰符

Using the #39;new#39; modifier in C#(在 C# 中使用“新修饰符)
本文介绍了在 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# 中使用“新"修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)