C#和隐藏方法 [英] C# and method hiding

查看:147
本文介绍了C#和隐藏方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每MSDN,用于隐藏方法时,新的关键字只是禁止警告。

Per MSDN, the "new" keyword when used for method hiding only suppresses a warning.

的http:// msdn.microsoft.com/en-us/library/435f1dw2.aspx

我真的需要这个新关键字来执行的方法隐藏?如果我有了同样的方法名称,但没有明确指出这是压倒一切的子类,是不是同样的事情基本上,我只是得到一个警告?请告诉我,如果我的理解是正确的。谢谢

Do I really need this "new" keyword to perform method hiding? If I have a child class that has the same method name but doesn't explicitly state that it is overriding, isn't that the same thing essentially, I just get a warning? Please tell me if my understanding is correct. Thanks

推荐答案

您get方法隐藏无论您是否指定新的,但它是不一样的压倒一切的。在此处,他们是不同的一个例子:

You get method hiding whether or not you specify "new", but it's not the same as overriding. Here's an example where they're different:

using System;

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

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

class Derived : Base
{
    public override void OverrideMe()
    {
        Console.WriteLine("Derived.OverrideMe");
    }

    public new void HideMe()
    {
        Console.WriteLine("Derived.HideMe");
    }
}

class Test
{
    static void Main()
    {
        Base x = new Derived();
        x.OverrideMe();
        x.HideMe();
    }
}



输出是:

The output is:

Derived.OverrideMe
Base.HideMe

尽管基 HideMe 方法是虚拟的,它不是在覆盖派生,这是只是被隐藏了 - 所以这种方法仍然是绑定到虚拟方法基本,而这正是被执行

Even though the base HideMe method is virtual, it isn't overridden in Derived, it's just hidden - so the method is still bound to the virtual method in Base, and that's what gets executed.

会员一般隐藏是一个坏主意,使得代码更难理解。这是事实可用的是版本而言是有利的,但是 - 这意味着添加一个方法到基类没有可能让派生类重写它无意的,他们可以继续像以前一样工作。这就是为什么你得到警告。

Member hiding is generally a bad idea, making the code harder to understand. The fact that it's available is beneficial in terms of versioning, however - it means adding a method to a base class doesn't potentially let derived classes override it unintentionally, and they can keep working as before. That's why you get the warning.

这篇关于C#和隐藏方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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