困惑"越权QUOT;与"新"在C#中 [英] Confused about "override" vs. "new" in C#

查看:171
本文介绍了困惑"越权QUOT;与"新"在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

class Base
{
    public virtual void Print()
    {
        Console.WriteLine("Base");
    }
}

class Der1 : Base
{
    public new virtual void Print()
    {
        Console.WriteLine("Der1");
    }
}

class Der2 : Der1
{
    public override void Print()
    {
        Console.WriteLine("Der2");
    }
}

这是我的主要方法:

Base b = new Der2();
Der1 d1 = new Der2();
Der2 d2 = new Der2();

b.Print();
d1.Print();
d2.Print();



输出为基本 DER2 DER2

据我所知,覆盖拿下'吨让以前的方法来运行,即使该指针指向他们。所以第一行应该输出 DER2 为好。然而基本就出来了。

As far as I know, Override won't let previous method to run, even if the pointer is pointing to them. So the first line should output Der2 as well. However Base came out.

这怎么可能?如何覆盖没有工作呢?

How is it possible? How the override didn't work there?

推荐答案

您从来没有真正的重写基本版本的打印()。你只用 Der1 一个单独的虚拟方法(同名)隐藏它。

You've never actually overriden the Base version of Print(). You've only hidden it with a separate virtual method (named the same) in Der1.

当您使用关键字的方法签名 - 你告诉编译器,这是碰巧具有相同的名称作为您的基地之一的方法的方法类 - 但没有其他关系。您可以使这种新方法的虚拟(如你所做的),但是这是不一样的重写基类的方法。

When you use the new keyword on a method signature - you are telling the compiler that this is a method that happens to have the same name as a method of one of your base classes - but has no other relation. You can make this new method virtual (as you've done) but that's not the same as overriding the base class method.

DER2 在覆盖打印你实际上是覆盖您在 Der1宣布新版本 - 不是版本是基本。埃里克利珀有出色答卷,以一个稍微不同的问题,可以帮助您如何虚方法在C#语言被视为原因。

In Der2 when you override Print you are actually overriding the 'new' version that you declared in Der1 - not the version is Base. Eric Lippert has an excellent answer to a slightly different question that may help you reason about how virtual methods are treated in the C# language.

在你的榜样,当你调用打印,你是通过类型的引用基本调用它在第一种情况C $ C>打印被调用。另外两个调用被分派到 Der1 的实现,因为在这种情况下,你实际上已经重写方法。

In your example, when you call Print, you are calling it in the first case through a reference of type Base - so the hidden (but not overriden) version of Print is called. The other two calls are dispatched to Der1's implementation, because in this case, you've actually overriden the method.

您可以阅读更多有关这一新的,覆盖 MSDN文档中

You can read more about this in the MSDN documentation of new and override.

你可能已经打算与Der1做(因为你DER2做的)是使用覆盖关键字:

What you may have intended to do with Der1 (as you did with Der2) is to use the override keyword:

class Base 
{ 
    public virtual void Print() 
    { 
        Console.WriteLine("Base"); 
    } 
} 

class Der1 : Base 
{ 
    // omitting 'new' and using override here will override Base
    public override void Print() 
    { 
        Console.WriteLine("Der1"); 
    } 
} 

这篇关于困惑"越权QUOT;与"新"在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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