2011-09-28 54 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

相关问题