Extension methods overloading in C#, does it work?

后端 未结 5 757
遥遥无期
遥遥无期 2020-12-11 17:27

Having a class that has a method, like this:

class Window {
    public void Display(Button button) {
        // ...
    }
}

is it possible

5条回答
  •  粉色の甜心
    2020-12-11 17:39

    Well, I believe this is a little tricky. If you pass Button as a method parameter:

    Button button = BlahBlah(o);
    window.Display(button);
    

    then there is suitable class method which always takes precedence over the extension method.

    But if you pass object that is not Button then there is no suitable class method and extension method will be invoked.

    var o = new object();
    window.Display(o);
    

    So, from what I see, your example should work correctly and extension method will call Display method on the Window instance. The infinite loop might be caused by some other code.

    Is there any chance that Window class containing Display method in your example and Window class that is a parameter to the extension method are actually two different classes?

提交回复
热议问题