问题
Possible Duplicate:
C# keyword usage virtual+override vs. new
Difference between new and override?
So I've been working on a project and decided to do some reading about the difference between the new
and override
keywords in C#.
From what I saw, it seems that using the new
keyword functionality is a great way to create bugs in the code. Apart from that I don't really see when it would actually make sense to use it.
More out of curiosity than anything, is there any pattern where the new
keyword is the right way to go?
回答1:
The new
keyword is the right way to go when you want to hide a base implementation and you don't care that you won't be able to call your method when treating your object polymorphically.
Let me clarify. Consider the following:
public class Base
{
public void DoSomething()
{
Console.WriteLine("Base");
}
}
public class Child : Base
{
public new void DoSomething()
{
Console.WriteLine("Child");
}
}
From time to time, it is beneficial to hide the base class' functionality in the child hence the use of the new
keyword. The problem is that some developers do this blindly which will lead to the following side effect (hence the 'bugs' you mention):
Base instance = new Child();
instance.DoSomething(); // may expect "Child" but writes "Base"
回答2:
One thing new
gives you is the ability to make it appear as if you can override a method that is not declared virtual. Keep in mind you are not overriding, but in fact declaring a method with the same name.
To use override
, the method has to be marked as virtual
or abstract
.
public class PolyTest
{
public void SomeMethod()
{
Console.WriteLine("Hello from base");
}
}
public class PolyTestChild : PolyTest
{
new public void SomeMethod()
{
Console.WriteLine("Hello from child");
}
}
Regarding your comment about buggy code, If the base implementation is doing something that you or the caller is expecting, that is where the bug is. However, I do not see that as any more dangerous than failing to call base.SomeMethod
(when overriding) and you need to.
回答3:
new
has its place and it is only considered a great way to right buggy code if you don't know how to use it.
One example:
public class A
{
public void AMethod() { }
}
public class B : A
{
public override void AMethod() { }
}
In this situation AMethod
cannot be overriden by B
because it is not virtual
or abstract
, so in order to provide a custom implementation you must use new
.
来源:https://stackoverflow.com/questions/9590243/when-to-use-new-instead-of-override-c-sharp