如何调用显式要求的接口方法的基类实现?
我正在尝试调用在基类上实现的显式实现的接口方法,但似乎无法让它工作。 我同意这个想法是丑陋的,但我已经尝试了我能想到的每一个组合,但无济于事。 在这种情况下,我可以改变基类,但我想我会问这个问题以满足我的普遍好奇心。
有任何想法吗?
// example interface interface MyInterface { bool DoSomething(); } // BaseClass explicitly implements the interface public class BaseClass : MyInterface { bool MyInterface.DoSomething() { } } // Derived class public class DerivedClass : BaseClass { // Also explicitly implements interface bool MyInterface.DoSomething() { // I wish to call the base class' implementation // of DoSomething here ((MyInterface)(base as BaseClass)).DoSomething(); // does not work - "base not valid in context" } }
你不能(它不是子类可用的接口的一部分)。 在那种情况下,使用类似的东西:
// base class bool MyInterface.DoSomething() { return DoSomething(); } protected bool DoSomething() {...}
然后任何子类都可以调用受保护的DoSomething()
或(更好):
protected virtual bool DoSomething() {...}
现在它可以覆盖而不是重新实现接口:
上述就是C#学习教程:如何调用显式要求的接口方法的基类实现?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public class DerivedClass : BaseClass { protected override bool DoSomething() { // changed version, perhaps calling base.DoSomething(); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1018287.html