如何从子类中调用基类中显式声明的接口成员?

Mar*_*eIV 8 c# overriding interface base

假设您可以访问实现"IFoo"的基类"MyClass".'IFoo'定义函数'int FooValue()','MyClass'显式实现它.现在假设您有一个名为'MySubClass'的'MyClass'的子类,并且您希望覆盖该子类中的'FooValue',但您还希望子类的实现基于基类实现的结果.

现在通常,这可以通过简单地将实现移动到基类中的受保护函数来解决,然后我们将简单地覆盖在子类中.做完了.但是我们无法访问基类的源代码.我们只将其作为库的参考.那你怎么解决这个问题呢?

不是重复(更新:......就像这一个)!

这里有这个问题...... C#:通过明确指定接口来覆盖属性 ...当你不能通过普通的通道本身覆盖基类的接口时,你可以明确地重新实现相同的接口子类,它的行为就像你覆盖了接口(但实际上你正在重新实现它,而不是覆盖它.)那就是说,我想弄清楚的是我如何得到基类的实现.(这就是为什么恕我直言,这不是那个问题的重复.)

这是基类的一些伪代码,我们再也无法访问代码......

public interface IFoo
{
    int FooValue();
}

public class MyClass : IFoo
{
    int IFoo.FooValue() <-- Explicit implementation requiring a cast to access.
    {
        return 4;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我们正在尝试做的事情,但显然这是不允许的,因为你不能像这样使用'base'.

public class MySubClass : MyClass
{
    int IFoo.FooValue()
    {
        int baseResult = ((IFoo)base).FooValue(); <-- Can't use 'base' like this
        return baseResult * 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Dmi*_*nko 0

显式接口实现意味着 IFoo.FooValue() 是私有的 (可以通过反射的方式检查):

  MethodInfo mi = typeof(MyClass).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(m => m.Name.EndsWith("IFoo.FooValue")).ToList()[0];

  if (mi.IsPrivate) {
    // And it is private.... 
  } 
Run Code Online (Sandbox Code Playgroud)

所以你不能调用继承的IFoo.FooValue()。

可能的途径

  public interface IFoo
  {
      int FooValue();
  }

  public class MyClass : IFoo
  {
      // This (main logic) should be inherited/override 
      protected virtual int CoreFooValue() 
      {
          return 4;
      }

      // Just a non-virtual interface method which is immutable
      int IFoo.FooValue() 
      {
          return CoreFooValue();
      }
  }

  public class MySubClass : MyClass {
      // Logic is changed, interface is not 
      protected override int CoreFooValue() 
      {
          return base.CoreFooValue() * 2;
      }
  }
Run Code Online (Sandbox Code Playgroud)

另请参见非虚拟接口模式

http://en.wikipedia.org/wiki/Non-virtual_interface_pattern