为什么忽略基类中声明的签名? [英] Why are signatures declared in the base class ignored?

查看:88
本文介绍了为什么忽略基类中声明的签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Base
{
    public virtual void MethodA(int x)
    {
        Console.WriteLine ("In Base Class");
    }
}

class Derived : Base
{
    public override void MethodA(int x)
    {
        Console.WriteLine ("In derived INT)");
    }

    public void MethodA(object o)
    {
        Console.WriteLine ("In derived OBJECT");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        int k = 20;
        d.MethodA(k);
    }
}

我得到的输出是在派生的OBJECT中。这种奇怪行为的原因是什么?经过一些研究,我发现原因是基类中声明的签名被忽略。他们为什么被忽视?

The output I got for this is "In derived OBJECT". What is the reason for this strange behaviour? After some research, I found out the reason is the signatures declared in the base class are ignored. Why are they ignored?

推荐答案

这是设计上有充分理由的。此设计有助于防止脆弱的基类问题。 C#旨在使编写版本化组件变得更容易和更安全,而这个规则是其中很重要的一部分。

This is by design and for a good reason. This design helps prevent the Brittle Base Class problem. C# was designed to make it easier and safer to write "versioned" components, and this rule is a big part of that.

这是一个非常常见的问题。这是我们得到的最常见的错误报告之一;也就是说,有人认为他们在编译器中发现了一个错误,实际上他们已经找到了一个功能。

This is a very frequently asked question. This is one of the most common "false bug reports" that we get; that is, someone believes they have found a bug in the compiler when in fact they have found a feature.

有关该功能的描述及其设计方式的原因是的,请参阅我关于这个主题的文章:

For a description of the feature and why it is designed the way it is, see my article on the subject:

http://blogs.msdn.com/b/ericlippert/archive/2007/09/04/future-breaking-changes-part- three.aspx

有关各种语言如何处理脆弱基类问题的更多文章,请参阅我关于该主题的文章存档:

For more articles on the subject of how various languages deal with the Brittle Base Class problem see my archive of articles on the subject:

http ://blogs.msdn.com/b/ericlippert/archive/tags/brittle+base+classes/

这篇关于为什么忽略基类中声明的签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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