C# - 关键字使用 virtual+override 与 new [英] C# - Keyword usage virtual+override vs. new

查看:34
本文介绍了C# - 关键字使用 virtual+override 与 new的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基类型virtual"中声明一个方法然后在子类型中使用override"关键字覆盖它与简单地使用有什么区别在子类型中声明匹配方法时的new"关键字?

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?

推荐答案

new"关键字不会覆盖,它表示一个与基类方法无关的新方法.

The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.

public class Foo
{
     public bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public new bool DoSomething() { return true; }
}

public class Test
{
    public static void Main ()
    {
        Foo test = new Bar ();
        Console.WriteLine (test.DoSomething ());
    }
}

这会打印假,如果您使用覆盖,它会打印真.

(基本代码取自 Joseph Daigle)

(Base code taken from Joseph Daigle)

因此,如果您正在执行真正的多态性,则应该始终覆盖.唯一需要使用new"的地方是该方法与基类版本没有任何关系.

So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.

这篇关于C# - 关键字使用 virtual+override 与 new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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