What is the difference between the override and new keywords in C#?

后端 未结 5 1178
无人共我
无人共我 2020-11-28 21:49

What is the difference between the override and new keywords in C# when defining methods in class hierarchies?

5条回答
  •  孤独总比滥情好
    2020-11-28 22:54

    Consider the following class hierarchy:

    using System;
    
    namespace ConsoleApp
    {     
         public static class Program
         {   
              public static void Main(string[] args)
              {    
                   Overrider overrider = new Overrider();
                   Base base1 = overrider;
                   overrider.Foo();
                   base1.Foo();
    
                   Hider hider = new Hider();
                   Base base2 = hider;
                   hider.Foo();
                   base2.Foo();
              }   
         }   
    
         public class Base
         {
             public virtual void Foo()
             {
                 Console.WriteLine("Base      => Foo");
             }
         }
    
         public class Overrider : Base
         {
             public override void Foo()
             {
                 Console.WriteLine("Overrider => Foo");
             }
         }
    
         public class Hider : Base
         {
             public new void Foo()
             {
                 Console.WriteLine("Hider     => Foo");
             }
         }
    }    
    

    Output of above codes must be:

    Overrider => Foo
    Overrider => Foo
    
    Hider     => Foo
    Base      => Foo
    
    • A subclass overrides a virtual method by applying the override modifier:
    • If you want to hide a member deliberately, in which case you can apply the new modifier to the member in the subclass. The new modifier does nothing more than suppress the compiler warning that would otherwise result

提交回复
热议问题