You've never actually overriden the Base
version of Print()
. You've only hidden it with a separate virtual method (named the same) in Der1
.
When you use the new
keyword on a method signature - you are telling the compiler that this is a method that happens to have the same name as a method of one of your base classes - but has no other relation. You can make this new method virtual (as you've done) but that's not the same as overriding the base class method.
In Der2
when you override Print
you are actually overriding the 'new' version that you declared in Der1
- not the version is Base
. Eric Lippert has an excellent answer to a slightly different question that may help you reason about how virtual methods are treated in the C# language.
In your example, when you call Print
, you are calling it in the first case through a reference of type Base
- so the hidden (but not overriden) version of Print
is called. The other two calls are dispatched to Der1
's implementation, because in this case, you've actually overriden the method.
You can read more about this in the MSDN documentation of new and override.
What you may have intended to do with Der1 (as you did with Der2) is to use the override
keyword:
class Base
{
public virtual void Print()
{
Console.WriteLine("Base");
}
}
class Der1 : Base
{
// omitting 'new' and using override here will override Base
public override void Print()
{
Console.WriteLine("Der1");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…