C#继承了实现接口的protected方法

dev*_*vio 3 c# inheritance class interface-implementation

我在C#中有这个类/接口定义

public class FooBase {
    ...
    protected bool Bar() { ... }
    ...
}

public interface IBar {
    bool Bar();
}
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个派生自FooBase实现IBar的类Foo1:

public class Foo1 : FooBase, IBar {
}
Run Code Online (Sandbox Code Playgroud)

是否存在一些类声明魔法,编译器将继承的受保护方法作为接口的可公开访问的实现?

当然是一种Foo1方法

bool IBar.Bar()
{
    return base.Bar();
}
Run Code Online (Sandbox Code Playgroud)

作品.我只是好奇是否有捷径;)

省略此方法会导致编译器错误:Foo1未实现接口成员IBar.Bar().FooBase.Bar()是静态的,不是公共的,或者返回类型错误.

说明:我将代码继承(类层次结构)和功能实现(接口)分开.因此,对于实现相同接口的类,访问共享(继承)代码非常方便.

Sam*_*ell 6

没有捷径.事实上,这个模式在我见过的几个地方使用过(不一定是ICollection,但你明白了):

public class Foo : ICollection
{
    protected abstract int Count
    {
        get;
    }

    int ICollection.Count
    {
        get
        {
            return Count;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)