Different behaviour of method overloading in C#

后端 未结 3 889
故里飘歌
故里飘歌 2020-12-09 11:14

I was going through C# Brainteasers (http://www.yoda.arachsys.com/csharp/teasers.html) and came across one question: what should be the output of this code?

         


        
3条回答
  •  一生所求
    2020-12-09 11:31

    It revolves around scope. In the first program, void Foo(int i) belongs to class Base. class Derived merely redefines its behavior.

    Foo(int i) is ignored because it's being "borrowed" and redefined via inheritance from class Base. if Foo(object o) did not exist, then Foo(int i) would be used.

    In the second program, void Foo(int i) is called because it properly belongs to class Derived (i.e. it's not being borrowed and overriden through inheritance) and has the best signature fit.

提交回复
热议问题