Why can you not invoke extension methods directly?

后端 未结 4 924
离开以前
离开以前 2021-01-11 16:13

Can someone explain to me why in the following the 3rd invocation of DoSomething is invalid? ( Error message is \"The name \'DoSomething\' does not exist in the current cont

4条回答
  •  借酒劲吻你
    2021-01-11 16:57

    Extension methods are still static methods, not true instance calls. In order for this to work you would need specific context using instance method syntax (from Extension Methods (C# Programming Guide))

    In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.

    So while normally, both syntaxes would work, the second is without explicit context, and it would seem that the IL generated can't obtain the context implicitly.

提交回复
热议问题