zoukankan      html  css  js  c++  java
  • 访问修饰符protected

    protected(C# 参考)

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

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

    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.
            // a.x = 10; 
    
            // OK, because this class derives from A.
            b.x = 10;
        }
    }

    语句 a.x = 10 生成错误,因为它是在静态方法 Main 中生成的,而不是类 B 的实例。

    结构成员无法受保护,因为无法继承结构。
    此示例中,DerivedPoint 类派生自 Point。 因此,可以从派生类直接访问基类的受保护成员。
    C#

        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.

  • 相关阅读:
    [Jobdu] 题目1528:最长回文子串
    [Jobdu] 题目1510:替换空格
    [Leetcode] Candy
    [Leetcode] Jump Game
    [Leetcode] Longest Valid Parentheses
    [Leetcode] Triangle
    [Leetcode] Populating Next Right Pointers in Each Node
    java web作用域page request session application
    String对象不可改变的特性及内存机制
    Java IO
  • 原文地址:https://www.cnblogs.com/gsk99/p/4975212.html
Copyright © 2011-2022 走看看