c# - 接口(interface)继承一致性

标签 c# silverlight inheritance interface implementation

先看这段代码:

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/

相关文章:

c# - C# 代码插入错误时回滚

C# - 使用 Linq 选择 XML 后代

c# - SQL CE 最大长度

javascript - 获取 Function.prototype.bind.apply(...) 不是构造函数错误

c++ - 从派生类成员初始化基类引用

c# - 继承:根据具体对象在运行时调用正确的方法

c# - 如何在动态选择的文件夹上创建一个 txt 文件

c# - 在 ItemCheck 事件后清除 CheckedListBox

wpf - ListBox 或 ItemsControl 项目不占用所有可用空间

silverlight - 如何以编程方式访问Silverlight FrameworkElement的ToolTipService?