C# and method hiding

后端 未结 9 1216
悲&欢浪女
悲&欢浪女 2021-01-03 07:48

Per MSDN, the \"new\" keyword when used for method hiding only suppresses a warning.

http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

Do I really need

9条回答
  •  离开以前
    2021-01-03 08:31

    You get method hiding whether or not you specify "new", but it's not the same as overriding. Here's an example where they're different:

    using System;
    
    class Base
    {
        public virtual void OverrideMe()
        {
            Console.WriteLine("Base.OverrideMe");
        }
    
        public virtual void HideMe()
        {
            Console.WriteLine("Base.HideMe");
        }
    }
    
    class Derived : Base
    {
        public override void OverrideMe()
        {
            Console.WriteLine("Derived.OverrideMe");
        }
    
        public new void HideMe()
        {
            Console.WriteLine("Derived.HideMe");
        }
    }
    
    class Test
    {
        static void Main()
        {
            Base x = new Derived();
            x.OverrideMe();
            x.HideMe();
        }
    }
    

    The output is:

    Derived.OverrideMe
    Base.HideMe
    

    Even though the base HideMe method is virtual, it isn't overridden in Derived, it's just hidden - so the method is still bound to the virtual method in Base, and that's what gets executed.

    Member hiding is generally a bad idea, making the code harder to understand. The fact that it's available is beneficial in terms of versioning, however - it means adding a method to a base class doesn't potentially let derived classes override it unintentionally, and they can keep working as before. That's why you get the warning.

提交回复
热议问题