Public, Private, Protected and Internal in C#

2008-08-28


**Access Modifiers **

(from: http://msdn.microsoft.com/en-us/library/ms173121.aspx)

All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. You specify the accessibility of a type or member when you declare it by using one of these access modifiers:

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it. \

private

The type or member can only be accessed by code in the same class or struct. 

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class. 

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly. 

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly. 

c# 类的public private internal protected的区别

C#的类和Java一样有影响的范围限制

public 修饰的类,可以在整个系统的任意地方调用,是完全公开的.

private 相反的,只能在类内部调用.任何实例,无法调用private调用.

internal 仅为同项目(这里的项目是只单独的项目,而不是整个解决方案)调用,按照我的理解,应该是和java的friendly一样的效果.

protected 自己及自己的子类可以调用

好象和java相差就一个internal和friendly

这三个修饰符如果修饰的都是类中的成员的话,public 修饰的成员可以被所有的类访问(本类,别的类,本类的子类),private修饰的成员只能被本类访问,protected修饰的成员只能被本类和本类的子类所访问。