我有一个受保护的类,我想成为公共类中的属性,但可以访问同一程序集中的派生类

时间:2012-07-25 18:58:45

标签: c# visibility internal protected

我正在使用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修饰符的行为类似于维恩图中protectedinternal的交集 - 它只能被同一个程序集中的实体访问是所述类的子类,其中属性/方法/构造函数/字段/任何存在。鉴于我的信念,我认为前面的代码应该编译。

1 个答案:

答案 0 :(得分:2)

protected internal不是protectedinternal交叉点,它是联合,这意味着{{1}所有类的后代都可以看到属性,无论它们在哪个程序集中。

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