C# private (hidden) base class

对着背影说爱祢 提交于 2019-12-23 07:25:55

问题


Is it possible to make a C# base class accessible only within the library assembly it's compiled into, while making other subclasses that inherit from it public?

For example:

using System.IO;

class BaseOutput: Stream           // Hidden base class
{
    protected BaseOutput(Stream o)
    { ... }

    ...lots of common methods...
}

public class MyOutput: BaseOutput  // Public subclass
{
    public BaseOutput(Stream o):
        base(o)
    { ... }

    public override int Write(int b)
    { ... }
}

Here I'd like the BaseOutput class to be inaccessible to clients of my library, but allow the subclass MyOutput to be completely public. I know that C# does not allow base classes to have more restrictive access than subclasses, but is there some other legal way of achieving the same effect?

UPDATE

My solution for this particular library is to make the base class public and abstract, and to document it with "Do not use this base class directly". I also make the constructor of the base class internal, which effectively prevents outside clients from using or inheriting the class.

(It's a shame, because other O-O languages let me have hidden base classes.)


回答1:


Unfortunately not. You can't derive a public class from an internal or private class.

You need to either expose the base class, or you need to declare all the methods for all of your similar classes. If you go the route where you declare all methods again, it's probably useful to create a helper class, which has the actual implementation of them. Still it's quite a bit of boilerplate.




回答2:


Consider a pattern such as a Facade. That's what they're there for. I don't think you can achieve what you require with straight inheritance.




回答3:


Depending on what "lot of common methods" are doing you may achieve some of it with internal extension methods:

internal static class MyStreamExtensions
{
   internal static int UsefulOne(this Stream stream)
   {
     return 42; 
   }
}   

Another approach is to make constructor internal to prevent unintentional derivation from that class:

public class BaseOutput: Stream
{
    internal BaseOutput(Stream o)
    { ... }

    ...lots of common methods...
}

This will make code more understandable compared to "not-really-visible" intermediate class in hierarchy.



来源:https://stackoverflow.com/questions/10858107/c-sharp-private-hidden-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!