我试图调用在基类上实现的显式实现的接口方法,但似乎无法让它工作。我同意这个想法很难看,但我已经尝试了我能想到的所有组合,但无济于事。在这种情况下,我可以更改基类,但我想我会问这个问题来满足我的一般好奇心。
有任何想法吗?
// 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() {...}
现在它可以只覆盖而不是重新实现接口:
public class DerivedClass : BaseClass
{
protected override bool DoSomething()
{
// changed version, perhaps calling base.DoSomething();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)