Protected在继承中的作用

常见访问修饰符

  • public :公共的、可见的
  • private :私有的
  • protected :受保护的

protected 在派生类中可以访问基类的该成员,实例化派生类后该成员不可访问,换个角度说,protected成员在派生类中成为private成员。后续还可以在下一个派生类中访问这个成员,仍然实例化后不可访问。

private 在派生类中访问不了基类的该成员,实例化后也不访问

public 派生后 实例化后都可以访问该成员

using System;
using System.Collections.Generic;
using System.Text;

namespace 访问修饰符
{
    class BaseTest 
    {
        public int a = 10;
        protected int b = 2;
        private int e = 3;
    }

    class Program:BaseTest
    {
        int c = 2;
        int d = 3;
        static void Main(string[] args)
        {
            BaseTest baseTest = new BaseTest();
            Program p = new Program();
            //Console.WriteLine(this.base.a;this.base.b);
            //Console.WriteLine(this.a;this.b;this.c;this.d);
            Console.ReadLine();
        }
    }
}

少见的访问修饰符

  • internal 对该程序集内所有类可访问
  • protected internal 对所有继承该类或在该程序集内声明的类可访问

Protected在继承中的作用_第1张图片

你可能感兴趣的:(C#)