1

我正在使用 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它只能被同一程序集中的实体访问,并且是属性/方法/构造函数/字段/存在的所述类的子类. 鉴于我的信念,我认为前面的代码应该可以编译。

4

1 回答 1

2

protected internal不是 and 的交集它是union,这意味着该属性将对类的所有后代可见,而不管他们在哪个程序集中。protectedinternalprotected internal

参考:http: //msdn.microsoft.com/en-us/library/ms173121.aspx

于 2012-07-25T19:01:42.063 回答