C# - Keyword usage virtual+override vs. new

后端 未结 10 2081
被撕碎了的回忆
被撕碎了的回忆 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:51

    The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.

    public class Foo
    {
         public bool DoSomething() { return false; }
    }
    
    public class Bar : Foo
    {
         public new bool DoSomething() { return true; }
    }
    
    public class Test
    {
        public static void Main ()
        {
            Foo test = new Bar ();
            Console.WriteLine (test.DoSomething ());
        }
    }
    

    This prints false, if you used override it would have printed true.

    (Base code taken from Joseph Daigle)

    So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.

提交回复
热议问题