protected internal class working within class but not working outside

拟墨画扇 提交于 2019-12-04 15:24:43

Look at the error.

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.

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

You may see Access Modifiers 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.

A class can't be protected except when it is inside another class.

The protected keyword is only valid for members of a class. In your second example, class B happens to be that member.

Think about it:
protected means: Derived classes can access this member.
As there is no such concept as derived namespaces, the protected keyword doesn't make sense for members of a namespace.

protected declares visiblity level for derived types.

In your first case you declare class inside namespace. There is no any polymophic support for namespaces, so there is no any sence of using protected classes in namespace

In second case, instead, you use it inside other classe (class A), which make it visible for all children of A class.

Anything that is not a member of an enclosing type (class) doesn't make sense at all to be protected. protected members are only for those to access who derives from your defined type that contains the member, and in the first example case you are missing that type definition.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!