访问修饰符

使用这些访问修饰符可指定下列五个可访问性级别:

public:访问不受限制。
protected:访问仅限于包含类或从包含类派生的类型。
Internal:访问仅限于当前程序集。
protected internal:访问仅限于当前程序集或从包含类派生的类型。
private:访问仅限于包含类型。



protected(C# 参考)
protected 关键字是一个成员访问修饰符。受保护成员在它的类中可访问并且可由派生类访问。
仅当访问通过派生类类型发生时,基类的受保护成员在派生类中才是可访问的。

 1// protected_keyword.cs
 2using System;
 3class A
 4{
 5    protected int x = 123;
 6}

 7
 8class B : A
 9{
10    static void Main()
11    {
12        A a = new A();
13        B b = new B();
14
15        // Error CS1540, because x can only be accessed by
16        // classes derived from A.
17        // a.x = 10; 
18        
19        // OK, because this class derives from A.
20        b.x = 10;   
21    }

22}

23

语句 a.x =10 将生成错误,因为 A 不是从 B 派生的。

结构成员无法受保护,因为无法继承结构。

在此示例中,类 DerivedPointPoint 派生;因此,可以从该派生类直接访问基类的受保护成员。

 1// protected_keyword_2.cs
 2using System;
 3class Point 
 4{
 5    protected int x;     protected int y;
 6}

 7
 8class DerivedPoint: Point 
 9{
10    static void Main() 
11    {
12        DerivedPoint dp = new DerivedPoint();
13
14        // Direct access to protected members:
15        dp.x = 10;        dp.y = 15;
16        Console.WriteLine("x = {0}, y = {1}", dp.x, dp.y); 
17    }

18}

19


 

posted @ 2008-06-08 10:17  <一路向西  阅读(150)  评论(0)    收藏  举报