[英]Is it possible to call the explicit interface implementation of the base class in c#?
我想编译该程序,然后在下面打印输出:
public interface IFoo
{
void Bar();
}
public class FooBase : IFoo
{
void IFoo.Bar()
{
Console.WriteLine("Hello from base class.");
}
}
public class Foo : FooBase, IFoo
{
void IFoo.Bar()
{
(base as IFoo).Bar(); // doesn't compile
Console.WriteLine("Foo added some behavior!");
}
}
public static class Program
{
public static void Main(string[] args)
{
var foo = new Foo() as IFoo;
foo.Bar();
}
}
所需的输出:
Hello from base class.
Foo added some behavior!
显然,上面的代码无法编译,因为这是使用base
关键字的无效方法。 有没有一种方法可以实现,而无需将基类中的实现更改为非显式的实现?
您可以简单地在基类中实现显式接口实现,以在类中为其实现实现调用受保护的方法。 这允许其他派生类在仍然显式实现接口的同时仍然调用该受保护的方法(并且也不会通过类型本身公开暴露接口的方法,这大概是实际目标)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.