Why is can't use overriding method in C#? (not about keyword)

隐身守侯 提交于 2019-12-10 12:07:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!