C# - Keyword usage virtual+override vs. new

后端 未结 10 2082
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:06

What are differences between declaring a method in a base type \"virtual\" and then overriding it in a child type using the \"override\" keyword as

10条回答
  •  孤独总比滥情好
    2020-11-22 06:53

    Here's some code to understand the difference in the behavior of virtual and non-virtual methods:

    class A
    {
        public void foo()
        {
            Console.WriteLine("A::foo()");
        }
        public virtual void bar()
        {
            Console.WriteLine("A::bar()");
        }
    }
    
    class B : A
    {
        public new void foo()
        {
            Console.WriteLine("B::foo()");
        }
        public override void bar()
        {
            Console.WriteLine("B::bar()");
        }
    }
    
    class Program
    {
        static int Main(string[] args)
        {
            B b = new B();
            A a = b;
            a.foo(); // Prints A::foo
            b.foo(); // Prints B::foo
            a.bar(); // Prints B::bar
            b.bar(); // Prints B::bar
            return 0;
        }
    }
    

提交回复
热议问题