[英]Invoking C# base class extension methods from inside derived class?
這是一個人為的例子:
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?
}
}
在上面的示例中,我試圖從派生的 class 調用分配給接口的擴展方法。 編譯器在這里失敗並說 MyMethod 在當前上下文中不存在。 我的 CS 文件中有所有適當的 using 語句,所以我不確定發生了什么。
嘗試像this
調用它:
this.MyMethod("test");
這是替代解決方案(我更喜歡):
(this as MyInterface).MyMethod("test");
為什么? - 因為之前提供的解決方案在擴展方法調用類的“新”方法(屬性也是一種方法)的情況下不起作用。 在這種情況下,您可能打算在基類/接口聲明的類型上調用擴展方法,這可能與派生類/接口的行為不同。
此外,此解決方案適用於“新”和“覆蓋”方法,因為虛擬“覆蓋”無論如何都會調用派生版本,這也是預期的。
編輯:如果您真的不想將“base”傳遞給擴展方法,而是允許它采用“this”,這可能無關緊要。 但是,您必須考慮行為差異。
此外,有趣的是作為對 Darin Dimitrov 評論的回答:擴展方法不需要實例來運行它們,因為它們是 static 方法。 您可以通過向其傳遞參數來調用擴展方法 static。 但是,“base”不是擴展方法聲明中標有“this”的參數的有效參數值,它(如果我是 MS)將允許簡化擴展方法的一般用法。
嘗試這樣調用它:
this.MyMethod("test");
將呼叫更改為
this.MyMethod("test")
此代碼編譯:
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.