C# · 12月 31, 2021

c# – 为什么不能直接调用扩展方法?

有人可以向我解释为什么在以下第三次调用DoSomething是无效的?
(错误消息是“当前上下文中不存在”DoSomething“的名称)” public class A { }public class B : A{ public void WhyNotDirect() { var a = new A(); a.DoSomething(); // OK this.DoSomething(); // OK DoSomething(); // ?? Why Not }}public static class A_Ext{ public static void DoSomething(this A a) { Console.WriteLine(“OK”); }}解决方法 扩展方法仍然是静态方法,而不是真实的实例调用.为了使其工作,您将需要使用实例方法语法(来自 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.

因此,通常情况下,两种语法都可以正常工作,第二种语言没有明确的上下文,而且生成的IL似乎不能隐含地获取上下文.