Can I make a type “sealed except for internal types”

落爺英雄遲暮 提交于 2019-12-08 15:50:35

问题


I want to make a type that can be inherited from by types in the same assembly, but cannot be inherited from outside of the assembly. I do want the type to be visible outside of the assembly.

Is this possible?


回答1:


You can make the constructor internal:

public class MyClass
{
    internal MyClass() { }
}

Every class that derives from a base class must call a constructor of the base class in its constructor. Since it can't call the constructor if the base class is in a different assembly, the derived class doesn't compile.




回答2:


I think this question could still benefit from a semantically correct answer... which is "no". You can't declare a type as "sealed to external assemblies only".

Don't get me wrong: dtb's answer is a good one. An internal constructor is the closest you can get from the desired result.

However, I think that anyone reading this should be aware that in this example, MyClass wouldn't be described as being sealed at runtime. It is unlikely that this will ever be a problem, but if may cause logic based on reflection (from your code or a 3rd party library) to act differently on this particular type. It's something to keep in mind.

And now, to further expand on dtb's sample code:

public class MyClass
{
    internal MyClass() { }

    // This factory method will be accessible from external assemblies, making your class instantiable yet still "sealed"
    public static MyClass Create()
    {
        return new MyClass();
    }
}

This way you can still create instances of MyClass from outside the owning assembly, while still keeping control over inheritance.



来源:https://stackoverflow.com/questions/3072119/can-i-make-a-type-sealed-except-for-internal-types

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