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似乎不能隐含地获取上下文.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...