您的位置:首页 > 编程语言 > C#

c# 类的public private internal protected的区别

2009-08-12 17:24 447 查看
在C#中,有如下几种修饰符,分别是public,protected,internal,private。先来看一下C# 4th Edition中的说明:

public

No restrictions. Members marked public are visible to any method of any class.

private

The members in class A that are marked private are accessible only to methods of class A.

protected

The members in class A that are marked protected are accessible to methods of class A and also to methods of classes derived from class A.

internal

The members in class A that are marked internal are accessible to methods of any class in A's assembly.

protected internal

The members in class A that are marked protected internal are accessible to methods of class A, to methods of classes derived from class A, and also to any class in A's assembly. This is effectively protected OR internal. (There is no concept of protected AND internal.)

public,protected,private这三个就不说了,来看一下internal和protected/internal的用法。

假设有类A如下:

public class A
{
protected int prot = 0;
public int publ = 0;

public void pub_func()
{ }

protected void prot_func()
{ }

internal void inter_func()
{ }

protected internal void prot_inter_func()
{ }

}

public class Tester :A {

static void Main( ) {

A a= new A( );
//a.inter_func();
//a.prot_inter_func();
//a.pub_func();//this.inter_func();
//this.prot_inter_func();
//this.pub_func();

}

}

如果在同一个程序集中,假如有一个类A,其它类中想要使用A中的属性或方法的话,不管是new方法产生的还是继承产生的,都可以访问到protected internal和internal的方法。

但是如果A类不是在同一个程序集中,就有很大的区别了,首先,你用new方法产生对象中,不可以使用protected internal或internal来访问。继承的方式可以访问到protected internal,但不可访问internal。

当你写的一些类,不想让外部访问,只想让它的子类范围内访问的话,使用protected internal可以起到很好的保护作用。

c# 类的public private internal protected的区别

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

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

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

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

<>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: