问题
public abstract class A
{
public void CallMe() { Console.WriteLine("I am A."); }
}
public class B : A
{
new public void CallMe() { Console.WriteLine("I am B."); }
}
class Program
{
static void Main(string[] args)
{
A a = new B();
a.CallMe();
}
}
output is "I am A."
Why this happening? Is this reasonable?
compiled by Visual Studio 2012.
回答1:
You need to make the CallMe() method in your base class virtual and then use the override modifier in B:
public abstract class A
{
public virtual void CallMe() { Console.WriteLine("I am A."); }
}
public class B : A
{
public override void CallMe() { Console.WriteLine("I am B."); }
}
回答2:
B.CallMe() does not override A.CallMe(), it shadows or hides A.CallMe(). Since CallMe is a non-virtual method the compiler chooses which method to call based on the compile time type of the a variable. Since the the compile time type of a is class A it will call A.CallMe().
If you want it to call B.CallMe() you need to use the virtual keyword on A.CallMe() which will enable virtual dispatch where the application will call the CallMe() method based on the runtime type of a which is class B.
See Hiding through inheritance
来源:https://stackoverflow.com/questions/23313408/why-is-cant-use-overriding-method-in-c-not-about-keyword