从派生类内部调用 C# 基类扩展方法?
这是一个人为的示例:
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?
}
}
在上面的示例中,我尝试从派生类调用分配给接口的扩展方法。编译器在此失败并表示当前上下文中不存在 MyMethod。我的 CS 文件中有所有适当的 using 语句,所以我不确定发生了什么。
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. The compiler fails here and says that MyMethod does not exist in the current context. I have all the appropriate using statements in my CS file, so I'm not sure what is going on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试像
this
一样调用它:Try invoking it like
this
:这是替代解决方案(我更喜欢):
为什么? - 因为前面提供的解决方案在扩展方法调用类的“新”方法(属性也是一种方法)的情况下不起作用。在这种情况下,您可能打算对基类/接口声明的类型调用扩展方法,该方法的行为可能与派生类/接口不同。
此外,该解决方案适用于“新”和“覆盖”方法,因为虚拟“覆盖”无论如何都会调用派生版本,这也是预期的。
编辑:如果您不想将“base”传递给扩展方法并允许它采用“this”,则这可能是无关紧要的。但是,您必须考虑行为差异。
另外,有趣的是,作为对 Darin Dimitrov 评论的回答:扩展方法不需要需要实例来运行它们,因为它们是静态方法。您可以通过向扩展方法传递参数来调用静态扩展方法。但是,对于扩展方法声明中标有“this”的参数,“base”不是有效的参数值,这(如果我是 MS)将允许简化扩展方法的一般用法。
Here is alternate solution (preferred by me):
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". 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. You can invoke an extension method as static by passing parameters to it. 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.
尝试这样称呼它:
Try calling it this way instead:
将调用更改为此
代码编译:
Change the call to
This code compiles: