先看这段代码:
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
我正在处理一个公开接口(interface)的 API,该接口(interface)在实现时将在处理的某个部分调用 DoWork
方法。
现在在上面的示例中,类 Base
是 API 的一部分,它在内部(在 API 中)已经显式地实现了该接口(interface)并在 DoWork< 中执行了一些重要的操作
方法。
我也需要在我的派生类中覆盖 IMethod
的实现,所以我会在需要时收到通知,问题是我无法“覆盖”该方法并调用基方法,我也不能将 base 转换为 IMethod
。
有什么解决办法吗?
注意:由于是Silveright项目,反射不会起作用,禁止私有(private)方法调用。
最佳答案
您是否可以只组合类,而不是使用继承?然后,您可以按照自己喜欢的方式实现 DoWork()
,并且仍然在 Base
对象上调用 DoWork()
。由于 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 设计者对显式接口(interface)实现做出了一个奇怪的选择,而你现在正在为此付出代价。
关于c# - 接口(interface)继承一致性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627611/