【发布时间】:2012-07-24 07:04:51
【问题描述】:
我正在使用 C# 4。
cmets 解释了类的目的以及为什么它们的结构是这样的。
/// <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 的交集——它只能被位于同一程序集中并且是所述类的子类的实体访问属性/方法/构造函数/字段/任何存在的地方。鉴于我的信念,我认为前面的代码应该可以编译。
【问题讨论】:
标签: c# visibility internal protected