首先看这段代码:
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");
}
}
Output:
Derived.DoWork
Desired:
Base.DoWork
Derived.DoWork
我正在处理一个 API,该 API 公开了一个接口,在实现该接口时,DoWork
方法将在游行的某些部分被调用。
现在在上面的例子中,类Base
是 API 的一部分,在内部(在 API 中)已经显式实现了该接口,并在DoWork
method.
我需要重写的实现IMethod
在我的派生类中也是如此,所以我在需要时会收到通知,问题是我无法“覆盖”该方法并调用基方法,也不能将基转换为IMethod
.
有什么解决办法吗?
Note:反射不起作用,因为它是 Silveright 项目,并且禁止调用私有方法。
您是否可以只组合类,而不是使用继承?然后你可以实施DoWork()
不管你喜欢什么,仍然可以打电话DoWork()
on the 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 设计者在显式接口实现方面做出了一个奇怪的选择,而你现在正在为此付出代价。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)