C# Extension method precedence

后端 未结 2 391
终归单人心
终归单人心 2021-01-11 12:21

I\'m a bit confused about how extension methods work.

If I\'m reading this correctly http://msdn.microsoft.com/en-us/library/bb383977.aspx and this If an extension

相关标签:
2条回答
  • 2021-01-11 12:57

    The big difference here is that you have defined an extension method for the IFoo interface, and your foo variable is of type IFoo.

    If your code was to look like this:

    Foo foo = new Foo();
    foo.Say()
    

    The Foo.Say() method would be executed, not the extension method.

    I wish I could give you a thorough explanation on why this is but I can only cover the basic mechanism. As your variable was of IFoo type and not of Foo, when the compiler tried to determine what methods were available, it looked past any non-interface methods of the Foo class (as it should). However, the extension method Say() was available, so it invoked this.

    0 讨论(0)
  • 2021-01-11 12:59

    In your Main, foo is declared as IFoo. When the compiler looks for a method Say, it finds only the extension method. This is because the instance method is declared in Foo, not in IFoo. The compiler doesn't know that the variable foo happens to contain a instance of Foo; it just looks at the type the variable is declared of.

    0 讨论(0)
提交回复
热议问题