简体   繁体   English

C#继承的受保护方法实现接口

[英]C# inherited protected method implementing interface

I have this class/interface definitions in C# 我在C#中具有此类/接口定义

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

public interface IBar {
    bool Bar();
}

Now I want to create a class Foo1 derived from FooBase implementing IBar: 现在,我想创建一个从FooBase派生的实现IBar的类Foo1:

public class Foo1 : FooBase, IBar {
}

Is there some class declaration magic that the compiler takes the inherited protected method as the publicly accessible implementation of the interface? 是否存在某种类声明魔术,编译器会将继承的受保护方法用作接口的公共可访问实现?

Of course, a Foo1 method 当然,Foo1方法

bool IBar.Bar()
{
    return base.Bar();
}

works. 作品。 I'm just curious whether there is a shortcut ;) 我很好奇是否有捷径;)

Omitting this method results in a compiler error: Foo1 does not implement interface member IBar.Bar(). 忽略此方法将导致编译器错误:Foo1不实现接口成员IBar.Bar()。 FooBase.Bar() is either static, not public, or has wrong return type. FooBase.Bar()是静态的,不是公共的或具有错误的返回类型。

Explanation: I separate code inheritance (class hierarchy) and feature implementation (interfaces). 说明:我将代码继承(类层次结构)和功能实现(接口)分开。 Thus for classes implementing the same interface, accessing shared (inherited) code is very convenient. 因此,对于实现相同接口的类,访问共享(继承)的代码非常方便。

No shortcut. 没有捷径。 In fact, this pattern is used in a few places I've seen (not necessarily with ICollection , but you get the idea): 实际上,此模式已在我见过的一些地方使用(不一定使用ICollection ,但您知道了):

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

    int ICollection.Count
    {
        get
        {
            return Count;
        }
    }
}

I believe your code is as short as it can be. 我相信您的代码会尽可能短。 Don't think there is any kind of shortcut out there. 不要以为有捷径可走。

The protected member FooBase.Bar() is not an implementation method of the interface IBar . 受保护的成员FooBase.Bar()不是接口IBar的实现方法。 The interface demands a public Method Bar() . 该接口需要一个公共的Method Bar()

There are 2 ways implementing an interface. 有两种实现接口的方法。 Explicit implementation or implicit implementation. 显式实现或隐式实现。

Following is explicit implementation . 以下是明确的实现 This method is called if an object of Foo is called through a IBar variable. 如果通过IBar变量调用Foo的对象,则调用此方法。

bool IBar.Bar() 
{
    return base.Bar();
}

Defining a public method Bar() is implicit implementation . 定义公共方法Bar()是隐式实现

To have the compiler satisfied you might override or new the baseclass method as public (not a good advise, if method is protected in baseclass). 为了使编译器满意,您可以覆盖或重新公开基类方法(如果方法在基类中受保护,则不建议这样做)。

new public bool Bar() 
{
    return base.Bar();
}

The trick is to implement an interface, but not having all interface members as public members in the class. 诀窍是实现一个接口,但不要让所有接口成员都作为类中的公共成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM