Why can't my public class extend an internal class?

前端 未结 5 1618
猫巷女王i
猫巷女王i 2020-12-01 07:16

I really don\'t get it.

If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why

5条回答
  •  鱼传尺愫
    2020-12-01 07:52

    I think you're mixing concerns here, and C# is to blame, actually (and Java before it).

    Inheritance should serve as a categorization mechanism, whereas it's often used for code reuse.

    For code reuse it's always been known that composition beats inheritance. The problem with C# is that it gives us such an easy way to inherit:

    class MyClass : MyReusedClass { }
    

    But in order to compose, we need to do it by ourselves:

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

    What's missing is a construct like a trait (pdf), which will bring composition to the same usability level as inheritance.

    There's research about traits in C# (pdf), and it would look something like this:

    class MyClass {
      uses { MyTrait; }
    }
    

    Although I'd like to see another model (that of Perl 6 roles).

    UPDATE:

    As a side note, the Oxygene language has a feature that lets you delegate all members of an interface to a member property that implements that interface:

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

    Here, all interface members of IReusable will be exposed through MyClass and they'll all delegate to the Reused property. There are some problems with this approach, though.

    ANOTHER UPDATE:

    I've begun implementing this automatic composition concept in C#: take a look at NRoles.

提交回复
热议问题