我正在使用 C# 4。
注释解释了类的目的以及为什么它们的结构是这样的。
/// <summary>
/// I want this internal just to reduce the number of publicly
/// accessible classes in this assembly. I don't want people to
/// come after me to even spend time reading about this class,
/// since it won't help them unless they're modifying, and not
/// using this assembly.
/// </summary>
internal class MyInternalClass
{
}
/// <summary>
/// This class is an initialization class for tests. This is the
/// base class for other initialization classes so that I can have
/// a tree-like structure of method calls. This needs to be
/// public because it is the base class of a derived class that needs
/// to be public.
/// </summary>
public class MyPublicClass
{
protected internal MyInternalClass MyInternalProperty;
}
/// <summary>
/// This class is a test class that tests a particular initialization
/// class. This class needst to be public, else the Unit Testing
/// framework will not execute its methods.
/// </summary>
public class MyInheritedPublicClass : MyPublicClass
{
}
谁能告诉我为什么上面的代码会出现不一致的可见性错误?
据我了解,这里是 C# 中可见性修饰符的含义:
public
:每个人,任何地方都可以看到和访问它,而无需任何形式的反射黑客。
private
:这只能在它声明的类的范围内访问。派生类和同一命名空间和程序集中的其他类看不到这一点。
protected
:这只能在它声明的类和任何派生类的范围内访问,无论程序集或命名空间如何,只要该类是公共的。如果类是内部的,那当然会进一步限制可以看到这个属性的类。
internal
:这只能由同一程序集中的实体访问。
我认为protected internal
修饰符的作用类似于维恩图中的交集protected
——internal
它只能被同一程序集中的实体访问,并且是属性/方法/构造函数/字段/存在的所述类的子类. 鉴于我的信念,我认为前面的代码应该可以编译。