c# delegate中的一些问题
class Program
{
static void Main(string[] args)
{
var car = new Car(15);
new Alerter(car); \\这个是什么意思呢
car.Run(120);
}
}
class Car
{
public delegate void Notify(int value);
public event Notify notifier;
private int petrol = 0;
public int Petrol
{
get { return petrol; }
set
{
petrol = value;
if (petrol < 10) //当petrol的值小于10时,出发警报
{
if (notifier != null)
{
notifier.Invoke(Petrol);
}
}
}
}
public Car(int petrol)
{
Petrol = petrol;
}
public void Run(int speed)
{
int distance = 0;
while (Petrol > 0)
{
Thread.Sleep(500);
Petrol--;
distance += speed;
Console.WriteLine("Car is running... Distance is " + distance.ToString());
}
}
}
class Alerter
{
public Alerter(Car car)
{
car.notifier += new Car.Notify(NotEnoughPetrol);
}
public void NotEnoughPetrol(int value)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("You only have " + value.ToString() + " gallon petrol left!");
Console.ResetColor();
}
}
中的static void Main(string[] args)
{
var car = new Car(15);
new Alerter(car); \\这个是什么意思呢
car.Run(120);
}
直接就是new Alerter(car); 是什么意思呢 没见过这样情况 求大神们解释下
[解决办法]
new Alerter(car);//在Alerter的构造函数里给car绑定事件
[解决办法]