C#中受保护访问修饰符Protected

在本文中,我将解释C#中的受保护的访问修饰符。

可以从声明它的类中访问受保护的成员,并且从从声明此成员的类中派生的任何类中都可以访问。
仅当访问通过派生类类型进行访问时,才可在派生类中访问基类的受保护成员。
它与私有相同,但允许派生类访问成员。
当我们想要使用程序中的继承概念时使用受保护的访问修饰符。

C# Protected修饰符示例

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

class Hello

{

    protected int x;

    protected int y;

}

class Hi : Hello

{

    public static void Main()

    {

       //Hello a = new Hello();

        //a.x = 10;

       //a.y = 15;

           Hi obj = new Hi();

      //Direct access to protected members:

        obj.x = 10;

        obj.y = 15;

        Console.WriteLine("x = {0}", obj.x);

        Console.WriteLine("y = {0}", obj.y);

        Console.ReadLine();

     }

}
日期:2020-04-11 23:03:48 来源:oir作者:oir