C# and method hiding

后端 未结 9 1224
悲&欢浪女
悲&欢浪女 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:26

    As far as I know, the only difference is the one you suggest: new hides the warning. I tried out the following code:

    class Base
    {
        public void Test(){}
    }
    
    class ChildA : Base
    {
        public void Test(){}
    }
    
    
    class ChildB : Base
    {
        public new void Test(){}
    }
    

    The test method for both classes look identical in IL:

    .method public hidebysig instance void  Test() cil managed
    {
      // Code size       1 (0x1)
      .maxstack  8
      IL_0000:  ret
    } // end of method ChildA::Test
    
    .method public hidebysig instance void  Test() cil managed
    {
      // Code size       1 (0x1)
      .maxstack  8
      IL_0000:  ret
    } // end of method ChildB::Test
    

    The compiler issued a warning for Test in ClassA, but not in ClassB. But as other answers has stated; don't confuse the concepts of method hiding and method overriding; not the same thing.

提交回复
热议问题