C#学习笔记002- 访问修饰符protected

书目 - 26页 - Listing 3-3

(摘自微软官方)

protected 关键字是一个成员访问修饰符。 受保护成员在其所在的类中可由派生类实例访问。

只有在通过派生类类型发生访问时,基类的受保护成员在派生类中才是可访问的。 例如,请看以下代码段:

class A
{
    protected int x = 123;
}

class B : A
{
    static void Main()
    {
        A a = new A();
        B b = new B();

        // Error CS1540, because x can only be accessed by 
        // classes derived from A. (错误CS1540,因为x只能通过从a派生的类来访问。)
        // a.x = 10;    
      
        // OK, because this class derives from A.
        b.x = 10;
    }
}

语句

a.x = 10

生成错误,因为它是在静态方法 Main 中生成的,而不是类 B 的实例。

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

此示例中,DerivedPoint类派生自Point。 因此,可以从派生类直接访问基类的受保护成员。

    class Point 
    {
        protected int x; 
        protected int y;
    }

    class DerivedPoint: Point 
    {
        static void Main() 
        {
            DerivedPoint dpoint = new DerivedPoint();

            // Direct access to protected members:(直接使用受保护的成员)
            dpoint.x = 10;
            dpoint.y = 15;
            Console.WriteLine("x = {0}, y = {1}", dpoint.x, dpoint.y); 
        }
    }
    // Output: x = 10, y = 15

如果将x和y的访问级别更改为 private,编译器将发出错误信息:

'Point.y' is inaccessible due to its protection level.(由于它的保护水平,它无法进入。)

'Point.x' is inaccessible due to its protection level.(由于它的保护水平,它无法进入。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值