从派生类内部调用C#基类扩展方法?

voi*_*ter 10 c# extension-methods

这是一个人为的例子:

public static class MyExtensions
{
  public static void MyMethod( this MyInterface obj, string txt )
  {
  }
}

interface MyInterface {}

public MyDerived : MyInterface
{
  void DoStuff()
  {
    MyMethod( "test" ); // fails; compiler can't find MyMethod?
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我试图调用从派生类分配给接口的扩展方法.编译器在这里失败,并说MyMethod在当前上下文中不存在.我在CS文件中有所有适当的using语句,所以我不确定是怎么回事.

Dar*_*rov 19

尝试调用它,如this:

this.MyMethod("test");
Run Code Online (Sandbox Code Playgroud)

  • @Robert Dailey,扩展方法总是需要一些实例来调用它们,并且在类的上下文中,它们在这个实例中被声明为`this`.这只是一个轻微*不便*,无法与您从中获得的所有好处相比:-) (2认同)