Does C# have the notion of private and protected inheritance?

前端 未结 10 1067
执笔经年
执笔经年 2020-12-16 09:02

Does C# have the notion of private / protected inheritance, and if not, why?

C++


class Foo : private Bar {
 public:
   ...
 }; 
         


        
10条回答
  •  死守一世寂寞
    2020-12-16 09:35

    First solution:

    protected internal acts as public in the same assembly and protected on other assemblies.

    You would need to change the access modifier of each members of the class which are not to be exposed through inheritance.

    It is a bit restrictive though that this solution requires and forces the class to be inherited to be used by another assembly. Thus the choice of being used only by inheritance or not is taken by the unknowing parent... normally the children are more knowing of the architecture...

    Not a perfect solution but might be a better alternative to adding an interface to hide methods and still leaving the possibility of using the parent methods to be hidden though the child class because you might not easily be able to force the use of the interface.


    Problem:

    The protected and private access modifiers cannot be used for methods that are implementing interfaces. That means that the protected internal solution cannot be used for interface implemented methods. This is a big restriction.


    Final solution:

    I fell back to the interface solution to hide methods.

    The problem with it was to be able to force the use of the interface so that members to be hidden are ALWAYS hidden and then definitely avoiding mistakes.

    To force using only the interface, just make the constructors protected and add a static method for construction (I named it New). This static New method is in fact a factory function and it returns the interface. So the rest of the code has to use the interface only!

提交回复
热议问题