首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

c# delegate中的一些有关问题

2013-02-05 
c# delegate中的一些问题class Program{static void Main(string[] args){var car new Car(15)new Aler

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绑定事件
[解决办法]

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

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

热点排行