简体   繁体   中英

Prevent inheritance of base class

If I have 3 classes as follows:

abstract class A {}

public class B : A {}

public class C: A {}

I want to force other code to use B or C directly, or inherit from either B or C . I don't want other code to inherit directly from A .

Is this even possible?

A cannot be private since B and C must be public, making A private would cause "Inconsistent accessibility". A can't be internal for the same reason.

Why do I want this?

I have designed an API, the response of which must include either property x, or both properties y & z, but not all 3. It also includes a bunch of other properties that are common to both possibilities. ie -

{
  "allOf": [
    {
      "type": "object",
      "properties": {
        "w": { ... }
      }
    }, 
    {
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "x": { ... }
          }
        }, 
        {
          "type": "object",
          "properties": {
            "y": { ... },
            "z": { ... }
          }
        }
      ]
    }
  ]
}

If you make B and C part of A you can mark the constructor of A private so no other classes can inherit directly from A :

public class A
{
    private A()
    {

    }

    public class B: A
    {
        public B()
        {

        }
    }

    public class C: A
    {
        public C()
        {

        }
    }
}

The downside however is that you now have to refer to B as AB (see edit, this is not needed), but functionality wise the rest of the application is able to instantiate and use classes of type AB and AC and inherit from them while prohibiting the ability to instantiate or use A directly (even in the same file/assembly).

So this is invalid anywhere outside of A :

public class D: A
{

}

But this you can use anywhere:

public class E : A.B
{

}

Edit: As noted by Jonathan Barclay you prevent having to use AB by the following using directive, which will allow you to inherit as normal:

using static MyNamespace.A;

public class D : B
{

}

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