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); 是什么意思呢 没见过这样情况 求大神们解释下

解决方案 »

  1.   

     new Alerter(car);//在Alerter的构造函数里给car绑定事件
      

  2.   

    那么这样写可以吗 car= new Alerter(car)
      

  3.   

    你是从那里抄滴“废代码”啊new Alerter(car); \\这个是什么意思呢这句能编译过去吗?
      

  4.   

    它这里不需要car对象做事,所以下面2个是一样的功能(都在构造函数里实现了)
    car= new Alerter(car);
          new Alerter(car);
    就想一个  public int DoSomeThing(){}函数,如果不需要返回值,你也可以直接调用
          DoSomeThing();
      

  5.   

    应该是这2个一样(它不需要alerter对象再做什么事情):
    Alerter alerter = new Alerter(car);
                      new Alerter(car);
      

  6.   

    new Alerter(car)只是注册了car的notifier事件。所以你在触发这个事件的时候,会调用Alerter的NotEnoughPetrol方法。