簡體   English   中英

是否可以在c#中調用基類的顯式接口實現?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM