受保护的内部类在班级内部工作,但不在外部工作

问题描述:

我尝试了一些事情,想知道为什么会这样.

I was trying few things and would like to know why this is happening so.

说,我在命名空间n中有一个名为A的类,并且我试图创建受保护的内部类B.

Say, I have a class called A in namespace n and I was trying to create protected internal class B.

namespace n
{
   public class A
   {
      public A()
      {
      }
   }
   protected internal class B //throwing error
   {
   }
}

但是当我这样尝试时(B作为A的子类),它没有抛出错误,并且构建成功.你能解释一下为什么会这样吗?

But when i try like this (B as a sub class of A), its not throwing error and its built success. Could you explain me why it is so?

namespace n
{
   public class A
   {
      public A()
      {
      }
      protected internal class B // its not throwing error
      {
      }
   }      
}

理论上我有什么遗漏吗?相当混乱.

Am i missing anything theoretically? Its quite a bit confusing.

查看错误.

在命名空间中定义的元素不能显式声明为 私有,受保护或受保护的内部

Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

只有内部成员或公共成员才可以在课程之外使用.

Only internal or public members are allowed outside the class.

第二种情况是将类B定义为类A的成员,这就是为什么您没有得到该错误的原因.

Your second case is defining the class B as member of class A that is why you are not getting the error.

您可能会看到访问修饰符C#

在命名空间中直接声明的类和结构(在 换句话说,它们没有嵌套在其他类或结构中)可以 公开或内部公开.如果没有访问权限,则默认为内部" 已指定修饰符.

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.