C# 不一致的可访问性:基类的可访问性低于类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13270414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inconsistent accessibility: base class is less accessible than class
提问by Ivan Prodanov
So I have an abstract base class in a DLL and child classes of that class. I want the childs to be public, but the base to be private so that it cannot be accessed outside of the dll.
所以我在 DLL 和该类的子类中有一个抽象基类。我希望孩子是公开的,但基础是私有的,这样就不能在 dll 之外访问它。
How do I do that?
我怎么做?
回答by Marc Gravell
You don't and you can't.
你没有,你也不能。
If you want to expose the class as public, the base-type mustbe public. One other option is to have a public interface, and only expose the type via the interface(presumably with a factory method somewhere for creating instances).
如果要将类公开为public,则基类型必须为public。另一种选择是使用public interface, 并且仅通过interface( 可能在某处使用工厂方法来创建实例)公开类型。
One final option is to encapsulatethe base-class rather than inherit it.
最后一种选择是封装基类而不是继承它。
回答by Liam
Just to clarify what I was saying in comments on @Marc Gravel's answer you could
只是为了澄清我在对@Marc Gravel 的回答的评论中所说的话,你可以
public ChildClass : ParentClass
{
}
public ParentClass
{
internal void MethodIdontWantToExpose()
{
}
}
That said an interfaceis probably the best solution
那说 aninterface可能是最好的解决方案
回答by Jon Hanna
Make it public, make all constructors internal(if you're using the default constructor, add a parameterless constructor to override that).
Make it public,制作所有构造函数internal(如果您使用的是默认构造函数,请添加一个无参数构造函数来覆盖它)。
Then while public and not sealed, it can't be sub-classed by external code.
然后,虽然公开且未密封,但不能由外部代码进行子类化。

