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

查看:110
本文介绍了C#-关键字用法virtual + override vs.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 ());
    }
}

此打印结果为false,如果您使用覆盖将打印为true.

(摘自Joseph Daigle的基本代码)

(Base code taken from Joseph Daigle)

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

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 vs.new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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