public :全部公开,在本程序集,其他程序集(Assembly)和继承类中均可访问。
//本程序集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyLib
{
public class Vehicle
{
public String Owner { get; set; }
}
public class Car:Vehicle
{
public void ShowOwner()
{
Console.WriteLine(this.Owner); //继承类、本程序集中使用public 变量
}
}
}
//另一程序集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyLib;
namespace HelloOOP
{
class Program
{
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle();
vehicle.Owner = "Timothy"; //在另一程序集使用
}
}
internal :默认访问级别,internal修饰的变量只可以在本程序集中使用,包括本程序集的继承类
//本程序集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyLib
{
public class Vehicle
{
internal String Owner { get; set; }
}
public class Car:Vehicle
{
public void ShowOwner()
{
Console.WriteLine(this.Owner); //继承类、本程序集中使用public 变量
}
}
}
在另一程序集引用则会报错
private:只可以在本程序段中使用,即在此大括号中。不能外部访问问,但是会继承在子类中,仅仅是没法通过点操作符直接访问罢了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyLib
{
public class Vehicle
{
private String Owner { get; set; }
}
public class Car:Vehicle
{
public void ShowOwner()
{
Console.WriteLine(this.Owner);
}
}
}
此时已经会报错:
protected:保护某一个方法或属性,使其不能直接作为属性暴露,但是创建他的子类时可以使用,范围可以是本程序集也可以是另一程序集,如
//本程序集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyLib
{
public class Vehicle
{
public String Owner { get; set; }
protected int _rpm; //protected 多用在方法上,可以和internal组合
private int _fuel;
public void Refuel()
{
_fuel = 100;
}
protected void Burn(int fuel)
{
_fuel-=fuel;
}
public void Accelerate()
{
_rpm += 1000;
Burn(1);
}
public int MySpeed
{
get { return _rpm / 100; }//只读
}
}
public class Car:Vehicle
{
public void ShowOwner()
{
Console.WriteLine(this.Owner);
}
public void TurboAccelerate()
{
Burn(2);
_rpm += 3000; //protected 修饰的变量在本程序集中的子类使用
}
}
}
//另一程序集
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyLib;
namespace HelloOOP
{
class Program
{
static void Main(string[] args)
{
Vehicle vehicle = new Vehicle();
vehicle.Owner = "Timothy";
vehicle.Accelerate();
vehicle.Accelerate();
Console.WriteLine(vehicle.MySpeed);
Car car = new Car();
car.TurboAccelerate();
Console.WriteLine(car.MySpeed);
Bus bus = new Bus();
bus.SlowAccelerate();
Console.WriteLine(bus.MySpeed);
}
}
class Bus : Vehicle
{
public void SlowAccelerate()
{
Burn(1);
_rpm += 500; //protected 修饰的变量在另一程序集中的子类使用
}
}
}