简体   繁体   English

我可以阻止一个类被非抽象对象继承吗?

[英]Can I prevent a class from being inherited by a non-abstract object?

Consider the following classes: 考虑以下类:

public abstract class Planet
{
    protected abstract Material Composition { get; }
}

public abstract class TerrestrialPlanet : Planet
{
    protected override Material Composition
    {
        get
        {
            return Type.Rocky;
        }
    }
}
public abstract class GasGiant : Planet
{
    protected override Material Composition
    {
        get
        {
            return Type.Gaseous;
        }
    }
}

Is there a way to prevent a non-abstract object from inheriting directly from class Planet ? 有没有办法阻止非抽象对象直接从类Planet继承?

In other words, can we enforce that any class that directly inherits from Planet be abstract? 换句话说,我们可以强制执行任何直接从Planet继承的类都是抽象的吗?

// ok, because it doesn't directly inherit from Planet
public class Earth : TerrestrialPlanet { ... }

// ok, because it is abstract
public abstract class IcyPlanet : Planet { ... }

// we want to prevent this
public class Pluto : Planet { ... }

No, you cannot prevent a non-abstract class from inheriting a given public class that you create. 不,您无法阻止非抽象类继承您创建的给定公共类。

If all of the classes deriving from the base will be in the same assembly, and none of the concrete classes will, you could make the base class internal , to avoid exposing it externally at all , which would prevent other assemblies from extending it directly. 如果所有从基地派生的类将在同一程序,并没有具体的类的会,可以使基类internal ,以避免将其暴露在外部的一切 ,这将阻止其他组件直接扩展它。 If it needs to be exposed publicly, or the concrete implementations will be in the same assembly, then this of course isn't an option. 如果它需要公开展示,或者具体实现将在同一个程序集中,那么这当然不是一种选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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