【问题标题】:C# inherited protected method implementing interfaceC#继承的受保护方法实现接口
【发布时间】:2010-11-17 23:48:55
【问题描述】:

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

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

public interface IBar {
    bool Bar();
}

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

public class Foo1 : FooBase, IBar {
}

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

当然是 Foo1 方法

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

有效。我只是好奇是否有捷径;)

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

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

【问题讨论】:

    标签: c# class inheritance interface-implementation


    【解决方案1】:

    我相信您的代码尽可能短。不要认为那里有任何捷径。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        受保护的成员FooBase.Bar()不是接口IBar的实现方法。该接口需要一个公共方法Bar()

        有两种实现接口的方法。显式实现或隐式实现。

        接下来是显式实现。如果通过 IBar 变量调用 Foo 的对象,则调用此方法。

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

        定义公共方法 Bar() 是隐式实现

        为了让编译器满意,您可以将基类方法覆盖或新建为公共方法(如果方法在基类中受保护,则不是一个好建议)。

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

        诀窍是实现一个接口,但不要将所有接口成员都作为类中的公共成员。

        【讨论】:

          猜你喜欢
          • 2020-09-09
          • 2015-03-26
          • 2016-03-17
          • 1970-01-01
          • 2016-06-12
          • 2014-06-09
          • 2016-09-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多