当直接从实现类访问接口成员不正确时,我们通常显式实现接口。天气它必须是内部的,否则会导致与 API 设计的冲突,或者当它增加滥用方法的机会时。
在我看来,绝对不鼓励为具有不同逻辑的多个接口单独实现成员,所以这里不是这种情况
编译器不允许将此类实现设为虚拟,因为它没有意义,我认为这是正确的。通常显式实现非常敏感,这就是您尝试隐藏它的原因。
但是我发现了以下覆盖显式实现的方式(它不是完全覆盖,而是它的作弊替代方案)
我发现这令人惊讶且非常失望。我的问题是为什么允许以下代码并且可以完美运行?我希望得到接口已经明确实现的错误。
这只是重现问题的基本示例
static void Main(string[] args)
{
var b = new Base();
((IInterface)b).Write();
var c = new Child();
((IInterface)c).Write();
}
public interface IInterface
{
void Write();
}
public class Base : IInterface
{
void IInterface.Write()
{
Console.WriteLine("Base");
}
}
public class Child : Base, IInterface // hack is here. Re Implemented :/
{
void IInterface.Write()
{
Console.WriteLine("Child");
}
}
Outputs
Base
Child