Why are signatures declared in the base class ignored?
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);
}
}
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?
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/
The compiler in VC# 2008 checks the available non-virtual functions before virtual ones, when deciding what to call. Since your Derived class has a non-virtual MethodA(object) that can be called, the compiler calls it.
If you add a virtual MethodA(object) to Base, then Derived.MethodA(int) will get called, because then both MethodA(object) and MethodA(int) are virtuals.
I'm not familiar enough with the C# language spec to know whether this is specified behavior, or a bug in the compiler.
精彩评论