C# · 12月 31, 2021

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

(错误消息是“当前上下文中不存在”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