首先看一下这段代码:
class Program
{
static void Main(string[] args)
{
var x =(Base) new Derived();
((IMethod)x).DoWork();
Console.ReadKey();
}
}
interface IMethod
{
void DoWork();
}
abstract class Base : IMethod
{
void IMethod.DoWork()
{
Console.WriteLine("Base.DoWork");
}
}
class Derived : Base, IMethod
{
public void DoWork()
{
//here I where I want to call base.DoWork();
Console.WriteLine("Derived.DoWork");
}
}
输出:
Derived.DoWork
所需:
Base.DoWork
Derived.DoWork
我正在处理一个暴露接口的API,该接口在实现时会在游行的某个部分调用DoWork
方法。
现在在上面的示例中,类Base
是API的一部分,在内部(在API中)已经显式实现了该接口,并在DoWork
方法中执行了一些重要的执行。 / p>
我还需要覆盖派生类中IMethod
的实现,所以我在需要时得到通知,问题是我不能“覆盖”方法并调用基本方法,也不能我将基础转换为IMethod
。
任何解决方案?
注意:反射不起作用,因为它是一个Silveright项目,并禁止私有方法调用。
答案 0 :(得分:3)
你能够只编写类,而不是使用继承吗?然后,您可以根据需要实施DoWork()
,并且仍然可以在DoWork()
对象上调用Base
。由于Base
是抽象的,因此您需要派生一个虚拟类型以使一切工作。
class Derived : IMethod
{
private class SneakyBase : Base
{
// abstract implementations here
}
private IMethod baseObject = new SneakyBase();
void DoWork()
{
baseObject.DoWork();
// Custom DoWork code here
}
}
以这种方式做事显然有点痛苦,但API设计人员通过显式接口实现做出了一个奇怪的选择,而你现在正在为此付出代价。
答案 1 :(得分:1)
您在寻找:
public class Derived : Base
{
public override void DoWork()
{
base.DoWork();
}
}
答案 2 :(得分:1)
我发现DanBryant's comment是答案,尽管他提到的有点冒险,因为我们无法保证实施者会调用基本方法,但这是一个不错的方式。
我创建了一个受保护的虚方法,从私有接口实现者调用,然后,在派生类中,而不是担心接口,我只关心覆盖基类并从中调用基本实现,这是有效的完美,例如:
abstract class Base : IMethod
{
void IMethod.DoWork()
{
DoWork();
}
protected virtual void DoWork()
{
Console.WriteLine("Base.DoWork");
}
}
class Derived : Base
{
protected override void DoWork()
{
base.DoWork();
//here I where I want to call base.DoWork();
Console.WriteLine("Derived.DoWork");
}
}