public | protected | private | |
---|---|---|---|
类的内部 | √ | √ | √ |
派生类的内部 | √ | √ | × |
类以及派生类的外部 | √ | × | × |
示例
using Console = System.Console;
namespace test;
public class Animal
{
private string pri;
protected string pro;
public string pub;
//构造函数
public Animal()
{
}
public Animal(string pri, string pro, string pub)
{
this.pri = pri;
this.pro = pro;
this.pub = pub;
}
//类的内部
public void AnimalInnerPrint()
{
Console.WriteLine("在类的内部访问");
Console.WriteLine(pri);
Console.WriteLine(pro);
Console.WriteLine(pub);
}
}
namespace test;
public class Dog:Animal
{
//构造函数
public Dog()
{
}
public Dog(string pri, string pro, string pub) : base(pri, pro, pub)
{
}
public void DogInnerPrint()
{
Console.WriteLine("在派生类dog的内部访问");
//private未能被派生类继承
//Console.WriteLine(pri);
Console.WriteLine(pro);
Console.WriteLine(pub);
}
}
using System;
namespace test;
public class Test
{
public static void Main()
{
Animal animal = new Animal("private","protected","public");
Dog dog = new Dog("private", "protected", "public");
animal.AnimalInnerPrint();
dog.DogInnerPrint();
//在类的外部访问
Console.WriteLine("在类的外部访问");
//Console.WriteLine(animal.pri);
//Console.WriteLine(animal.pro);
Console.WriteLine(animal.pub);
}
}
运行截图
结论
C#通过访问控制符限制访问权——
- 通过private保护自身
- 通过protected将成员以及继承给派生类的成员予以保护
- 通过public暴露给外部以供使用