2011-09-28 18 views
4

我想調用一個顯式實現的基類上實現的接口方法,但似乎無法讓它工作。我同意這個想法很糟糕,但我試過了所有我能想到的組合,但都無濟於事。在這種情況下,我可以改變基礎類,但是我認爲我會問這個問題來滿足我一般的好奇心。如何調用顯式強制接口方法的基類實現?

任何想法?

// example interface 
interface MyInterface 
{ 
    bool DoSomething(); 
} 

// BaseClass explicitly implements the interface 
public class BaseClass : MyInterface 
{ 
    bool MyInterface.DoSomething() 
    { 
    } 
} 

// Derived class 
public class DerivedClass : BaseClass 
{ 
    // Also explicitly implements interface 
    bool MyInterface.DoSomething() 
    { 
     // I wish to call the base class' implementation 
     // of DoSomething here 
     ((MyInterface)(base as BaseClass)).DoSomething(); // does not work - "base not valid in context" 
    } 
} 

回答

7

您不能(它不是可用於子類的接口的一部分)。在這種情況下,使用這樣的:

// base class 
bool MyInterface.DoSomething() 
{ 
    return DoSomething(); 
} 
protected bool DoSomething() {...} 

那麼任何一個子類可以調用保護DoSomething(),或(更好):

protected virtual bool DoSomething() {...} 

現在,它可以只覆蓋而不是重新實現接口:

public class DerivedClass : BaseClass 
{ 
    protected override bool DoSomething() 
    { 
     // changed version, perhaps calling base.DoSomething(); 
    } 
} 
+0

謝謝馬克 - 想通了。 – cristobalito

+0

@cristobalito作爲一邊......你*可以*更直接地在VB.NET中做到這一點;但是,這並不足以改變語言; p –

+0

沒有發生這種情況的機會馬克! – cristobalito

相關問題