【问题标题】:C# Interfaces- only implement an interface in other interfacesC#接口——只在其他接口中实现一个接口
【发布时间】:2010-02-17 18:41:03
【问题描述】:

我只想在其他接口中实现某些接口,我不希望它们能够被类直接继承。

提前致谢!

【问题讨论】:

  • 我重新阅读了这个问题,我仍然认为你需要一个例子
  • 再次阅读问题,我认为您要求一些构造来防止在类中直接实现接口,同时不阻止其他接口从它继承。
  • 示例:我有一个名为 IAnimation 的接口,我希望只通过接口 INonAnimated 或 IAnimated 来实现这个接口。这样,两个子接口都拥有相同的基本规则。
  • 也许将 IAnimation 接口作为 Abstract 将允许您从 IAnimation 派生另外两个接口,因为您无法创建它的对象,只能从它派生。
  • 我想这样做是为了“有条件地要求”一个属性/方法或另一个,但不是两者都需要;所有这些同时在父“抽象接口”中维护一些共享属性/方法。

标签: c# inheritance interface


【解决方案1】:

您不能在 C# 中执行此操作 - 任何类都可以实现它有权访问的任何接口。

您为什么要这样做?请记住,通过声明接口继承:

public interface InterfaceA {}
public interface InterfaceB : InterfaceA {}

您指定任何实现InterfaceB 的东西也必须实现InterfaceA,所以无论如何您都会得到实现InterfaceA 的类。

【讨论】:

  • public interface InterfaceA {} public interface InterfaceB : InterfaceA {} public interface InterfaceC : InterfaceA {} InterfaceA 将包含我将在 InterfaceB 和 InterfaceC 中使用的通用 [i]rules[/i] /跨度>
【解决方案2】:

首先,说“在其他接口中实现”是没有意义的,因为接口不能实现任何东西。

我可以看到两种有缺陷的方法。

  1. 制作实现 IAnimation 的 Animated 和 NonAnimated 抽象类。它们下面的具体类仍然可以使用 new 运算符强制覆盖您的 IAnimation 方法:

    class SomeAnim : Animated
    {
        public new void Foo() { }
    }
    
  2. 使用混合。将 IAnimated 和 INonAnimated 保留为接口,但不要在接口中放置任何方法。而是像这样定义扩展方法:

    static class Ext
    {
        public static void Foo(this IAnim anim)
        {
            if (anim is IAnimated) // do something
            else if (anim is INonAnimated) // do something else
        }
    }
    

再次,有点骇人听闻。但是无论如何,您尝试做的事情都表明存在设计缺陷。

【讨论】:

【解决方案3】:

我能建议的最好的方法是将它们——顶层接口和下降接口放在一个单独的程序集中,将基本接口声明为internal,将这些接口扩展为@987654322 @。

【讨论】:

  • 如果实现类无法访问超级接口,是否可以实际实现顶级接口?
  • 我明白了:Inconsistent accessibility: base interface 'IBaseInterface' is less accessible than interface 'IDescendantOfBaseInterface'。 C# 4.0。
猜你喜欢
  • 2011-02-17
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多