private : 私有成员, 在类的内部才可以访问。
protected : 保护成员,该类内部和继承类中可以访问。
public : 公共成员,完全公开,没有访问限制。
internal: 在同一命名空间内可以访问。
Demo :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Netaudition
{
/// <summary>
/// Example:简述public,private,protect,internal
/// </summary>
class Program
{
public class Animal {
public String Name { get; set; } //公共成员,完全公开,没有访问限制。
protected void eat() //保护成员,该类内部和继承类中可以访问。
{
Console.WriteLine("我是动物,我想吃什么就吃什么");
}
private int Age { get; set; } // 私有成员, 在类的内部才可以访问。
private void Sing() //在类的内部进行访问
{
Console.WriteLine("我是" + this.Name + "我今年" + this.Age);
}
internal void hobby() {
Console.WriteLine("我是热爱写代码的动物");
}
}
class Cat:Animal { //继承类访问
public void Print() {
Cat cat = new Cat();
cat.eat();
}
}
static void Main(string[] args)
{
Animal animal = new Animal();
Cat cat = new Cat();
cat.Print();
animal.Name = "小黑";
Console.ReadLine();
}
}
}