C#关键字的使用虚拟+覆盖与新 [英] C# keyword usage virtual+override vs. new

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

问题描述

什么是声明在基类的方法虚拟,然后使用覆盖的关键字覆盖在一个子类,而不是在孩子声明匹配的方法时,仅仅使用了新的关键字的区别类型?

What is the difference 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?

推荐答案

新的关键字不会覆盖,这意味着无关与基类方法的新方法。

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 ());
    }
}

这将打印假的,如果你使用的覆盖,将印有真实的。

(从约瑟夫·英对照精华文章采取基地code)

(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#关键字的使用虚拟+覆盖与新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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