C# protected修饰词
概述:
假设A为基类,B为子类,被protected修饰的成员在基类中
1. 在A中可直接访问
2. 在B中可直接访问;
3. 在A中通过A或B的实例访问;
4. 在B中通过B的实例访问,不能通过A的实例访问;
5. 在A和B外部的类中,无法访问;
总结:
基类中访问无限制;子类中直接访问或通过子类实例访问
代码示例:
using System;
namespace TestProtected
{
class Program
{
static void Main(string[] args)
{
var baseClass = new BaseClass();
var childClass = new ChildClass();
Console.WriteLine(baseClass.Member1);
// Console.WriteLine(baseClass.Member2);//不能访问
// baseClass.Function2();//不能访问
Console.WriteLine(childClass.Member1);
// Console.WriteLine(childClass.Member2);//不能访问
//childClass.Function2();//不能访问
}
}
public class BaseClass
{
public int Member1 = 100;
protected int Member2 = 200;
public int Member3;
public void Function1()
{
Member3 = Member2;
Function2();
var baseClass = new BaseClass();
var childClass = new ChildClass();
Console.WriteLine(baseClass.Member1);
Console.WriteLine(baseClass.Member2);
baseClass.Function2();
Console.WriteLine(childClass.Member1);
Console.WriteLine(childClass.Member2);
childClass.Function2();
}
protected void Function2()
{
Console.WriteLine("Function2");
}
}
public class ChildClass : BaseClass
{
public void Test()
{
Console.WriteLine(Member1.ToString());
Console.WriteLine(Member2.ToString());
Function2();
var baseClass = new BaseClass();
var childClass = new ChildClass();
Console.WriteLine(baseClass.Member1);
//Console.WriteLine(baseClass.Member2);//不能访问
//baseClass.Function2();//不能访问
Console.WriteLine(childClass.Member1);
Console.WriteLine(childClass.Member2);//不能访问
childClass.Function2();//不能访问
}
}
}