代码之家  ›  专栏  ›  技术社区  ›  David

为什么我的公共类不能扩展内部类?

  •  41
  • David  · 技术社区  · 14 年前

    我真的不明白。

    如果基类是抽象的,并且只用于向程序集中定义的公共子类提供公共功能,为什么不将其声明为内部的呢?

    5 回复  |  直到 12 年前
        1
  •  40
  •   Justin Niessner    14 年前

    通过从类继承,可以通过子类公开基类的功能。

    不能通过实现具有更高可见性的子类来违反父类的保护级别。

    如果基类真的要被公共子类使用,那么还需要将父类公开。

    另一种选择是将“父”保持在内部,使其非抽象,并使用它来组成子类,并使用接口强制类实现功能:

    public interface ISomething
    {
        void HelloWorld();
    }
    
    internal class OldParent : ISomething
    {
        public void HelloWorld(){ Console.WriteLine("Hello World!"); }
    }
    
    public class OldChild : ISomething
    {
        OldParent _oldParent = new OldParent();
    
        public void HelloWorld() { _oldParent.HelloWorld(); }
    }
    
        2
  •  44
  •   Eric Lippert    12 年前

    更新:这个问题 the subject of my blog on November 13th of 2012 . 更多关于这个问题的想法,请参阅。谢谢你的好问题!


    这是原C#设计师的设计决定。不幸的是,我现在不在我的办公桌上——我要休息几天来度过漫长的周末——所以我面前没有1999年的语言设计笔记。如果我回来后想一想,我会浏览一下,看看这个决定是否有道理。

    . 我尽量避免将继承用作 . 正如其他人所提到的,如果您想要表示的是“这个类与其他类共享实现机制”,那么最好选择组合而不是继承。

        3
  •  17
  •   Samuel    14 年前

    我认为你能做的最接近的事情就是阻止其他程序集创建抽象类,方法是将它的构造函数设置为内部的 MSDN :

    内部构造函数防止抽象类用作与抽象类不在同一程序集中的类型的基类。

    EditorBrowsableAttribute 或者将基类放在嵌套的命名空间中,例如 MyLibrary.Internals

        4
  •  4
  •   Jordão    13 年前

    我认为你在这里混淆视听,事实上,C是罪魁祸首(还有之前的Java)。

    class MyClass : MyReusedClass { }
    

    但为了创作,我们需要自己动手:

    class MyClass {
      MyReusedClass _reused;
      // need to expose all the methods from MyReusedClass and delegate to _reused
    }
    

    trait (pdf) ,这将使组合达到与继承相同的可用性级别。

    有关于 traits in C# (pdf) ,它看起来像这样:

    class MyClass {
      uses { MyTrait; }
    }
    

    尽管我想看看 another model (perl6角色的角色)。

    更新:

    作为旁注,Oxygene语言 a feature 使您可以将接口的所有成员委派给实现该接口的成员属性:

    type
      MyClass = class(IReusable)
      private
        property Reused : IReusable := new MyReusedClass(); readonly;
          implements public IReusable;
      end;
    

    IReusable 将通过 MyClass Reused 财产。有一些 problems 不过,用这种方法。

    另一个更新:

    我已经开始在C语言中实现这个自动合成的概念:看看 NRoles .

        5
  •  3
  •   Dave    14 年前