Calling child class method from parent

后端 未结 3 1022
故里飘歌
故里飘歌 2021-02-19 12:20

Is it possible for the a.doStuff() method to print \"B did stuff\" without editing the A class? If so, how would I do that?

class Program
{
    static void Main         


        
3条回答
  •  情话喂你
    2021-02-19 12:59

    The code for class A & B you have posted will anyways generate below compiler warning and will ask to use the new keyword on class B, although it will compile: The keyword new is required on 'B.doStuff()' because it hides inherited member 'A.doStuff()'

    Use method hiding along with new and virtual keyword in class Mapper and class B as follows:

    class Program
    {
        static void Main(string[] args)
        {
            Mapper a = new B(); //notice this line
            B b = new B();
    
            a.doStuff();
            b.doStuff();
    
            Console.ReadLine();
        }
    }
    
    class A
    {
        public void doStuff()
        {
            Console.WriteLine("A did stuff");
        }
    }
    
    class Mapper : A
    {
        new public virtual void doStuff() //notice the new and virtual keywords here which will all to hide or override the base class implementation
        {
            Console.WriteLine("Mapper did stuff");
        }
    }
    
    class B : Mapper
    {
        public override void doStuff()
        {
            Console.WriteLine("B did stuff");
        }
    }
    

提交回复
热议问题