简体   繁体   中英

How to prevent a class from being inherited outside the library, while being inherited by public classes?

Suppose I have the following classes in a library

public abstract class HiddenBaseClass
{
    //stuff
}
public abstract class ClassA : HiddenBaseClass
{
    //stuff
}
public abstract class ClassB : HiddenBaseClass
{
    //stuff
}

I want to prevent HiddenBaseClass from being inherited outside the library, but I do want ClassA and ClassB to be inherited. I cannot make HiddenBaseClass an internal class , because that would mean HiddenBaseClass is less accessible than ClassA and ClassB .

Is there a way around this?

Contrary to the comments on the question, I believe this scenario can make sense, if HiddenBaseClass has aspects that you need to rely on being implemented internally (because you trust the internal implementations), but expose other abstract operations for external code to implement. It may not be an appropriate design for your use case, but it's not unreasonable.

One simple way to make it impossible to inherit from it directly outside the same library is to give it an internal constructor:

public abstract class HiddenBaseClass
{
    // Only classes in the same assembly can chain to this constructor.
    internal HiddenBaseClass() {}
}

So long as all the constructors in the class are internal (or private protected, or private) that will prevent classes in other assemblies from chaining their constructors to the base class constructors, thus preventing inheritance.

As the comments so politely pointed out, this isn't the best structure for this kind of scenario. In the end I'm going for an implementation like this:

internal sealed class HiddenBaseClass
{
    //stuff
}
public abstract class ClassA
{
    internal HiddenBaseClass { get; set; }
    //stuff that uses HiddenBaseClass
}
public abstract class ClassB
{
    internal HiddenBaseClass { get; set; }
    //more stuff
}

I apologise for asking the wrong questions yet again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM