Calling child class method from parent

后端 未结 3 1006
故里飘歌
故里飘歌 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 13:13

    Yes, if you declare doStuff as virtual in A and then override in B.

    class A
    {
        public virtual void doStuff()
        {
            Console.WriteLine("A did stuff");
        }
    }
    
    class B : A
    {
        public override void doStuff()
        {
            Console.WriteLine("B did stuff");
        }
    }
    

提交回复
热议问题