简体   繁体   English

从派生的 class 内部调用 C# 基础 class 扩展方法?

[英]Invoking C# base class extension methods from inside derived class?

This is a contrived example:这是一个人为的例子:

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?
  }
}

In my example above, I'm trying to call an extension method assigned to an interface from my derived class.在上面的示例中,我试图从派生的 class 调用分配给接口的扩展方法。 The compiler fails here and says that MyMethod does not exist in the current context.编译器在这里失败并说 MyMethod 在当前上下文中不存在。 I have all the appropriate using statements in my CS file, so I'm not sure what is going on.我的 CS 文件中有所有适当的 using 语句,所以我不确定发生了什么。

Try invoking it like this :尝试像this调用它:

this.MyMethod("test");

Here is alternate solution (preferred by me):这是替代解决方案(我更喜欢):

(this as MyInterface).MyMethod("test");

Why?为什么? - because the solution provided previously will not work in cases when extension method calls class's "new" method (property is a method too). - 因为之前提供的解决方案在扩展方法调用类的“新”方法(属性也是一种方法)的情况下不起作用。 In such cases you may intend to call an extension method on the type declared by the base class/interface, which might behave differently from the derived class/interface.在这种情况下,您可能打算在基类/接口声明的类型上调用扩展方法,这可能与派生类/接口的行为不同。

Also, this solution will work for both "new" and "override" methods, because virtual "override" will anyway invoke derived version, which would be also intended.此外,此解决方案适用于“新”和“覆盖”方法,因为虚拟“覆盖”无论如何都会调用派生版本,这也是预期的。

EDIT: this may be irrelevant if you don't really want to pass "base" to the extension method and instead allow it take "this".编辑:如果您真的不想将“base”传递给扩展方法,而是允许它采用“this”,这可能无关紧要。 However, you must consider behavioral differences.但是,您必须考虑行为差异。

Also, interesting to note as an answer to the comment by Darin Dimitrov: extension methods don't require instance to run them, because they are static methods.此外,有趣的是作为对 Darin Dimitrov 评论的回答:扩展方法不需要实例来运行它们,因为它们是 static 方法。 You can invoke an extension method as static by passing parameters to it.您可以通过向其传递参数来调用扩展方法 static。 However, "base" is not a valid parameter value for parameter marked with "this" in the extension method declaration, which (if I were MS), would allow to simplify general usage of extension methods.但是,“base”不是扩展方法声明中标有“this”的参数的有效参数值,它(如果我是 MS)将允许简化扩展方法的一般用法。

Try calling it this way instead:尝试这样调用它:

this.MyMethod("test");

Change the call to将呼叫更改为

this.MyMethod("test")

This code compiles:此代码编译:

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

public interface MyInterface {}

public class MyDerived : MyInterface
{
  void DoStuff()
  {
    this.MyMethod( "test" ); // works now
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM