zoukankan      html  css  js  c++  java
  • 看到个委托事件问题

    问题大致上就是:加速,减速两个功能,速度达到设定值就减速

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             CarEven car = new CarEven();
     6             car.MaxSpeed = 180;
     7             UpSpeed up = new UpSpeed(car);
     8             DownSpeed down = new DownSpeed(car);
     9             for(int i=0;i<205;i++){
    10                 car.Speed();
    11             }
    12             Console.ReadLine();
    13         }
    14     }
    15     //速度
    16     public delegate void SpeedEventHandler();
    17 
    18     public class CarEven{
    19         //速度事件
    20         public event SpeedEventHandler SpeedEvent;
    21         public int CurrSpeed { get; set; }
    22         public int MaxSpeed { get; set; }
    23 
    24         public CarEven()
    25         {
    26             CurrSpeed = 0;
    27         }
    28 
    29         public void Speed()
    30         {
    31             SpeedEvent();
    32         }
    33     }
    34 
    35     public class UpSpeed{
    36         CarEven car;
    37         public UpSpeed(CarEven car)
    38         {
    39             this.car = car;
    40             car.SpeedEvent +=new SpeedEventHandler(car_SpeedEvent); // 订阅事件
    41         }
    42         void car_SpeedEvent()
    43         {
    44             if (car.CurrSpeed < car.MaxSpeed)
    45             {
    46                 Console.WriteLine("踩下油门,当前速度:{0}", car.CurrSpeed);
    47                 car.CurrSpeed++;
    48             }
    49         }
    50     }
    51 
    52     public class DownSpeed{
    53         CarEven car;
    54         public DownSpeed(CarEven car)
    55         {
    56             this.car = car;
    57             car.SpeedEvent +=new SpeedEventHandler(car_SpeedEvent); // 订阅事件
    58         }
    59         void car_SpeedEvent()
    60         {
    61             if (car.CurrSpeed >= car.MaxSpeed)
    62             {
    63                 Console.WriteLine("踩下刹车,当前速度:{0}", car.CurrSpeed);
    64                 car.CurrSpeed = car.CurrSpeed - 10;
    65             }
    66         }
    67     }

    一直没搞懂委托,最近打算弄懂它,不知道这样写对不对

  • 相关阅读:
    my first android test
    VVVVVVVVVV
    my first android test
    my first android test
    my first android test
    ini文件
    ZZZZ
    Standard Exception Classes in Python 1.5
    Python Module of the Week Python Module of the Week
    my first android test
  • 原文地址:https://www.cnblogs.com/margin-gu/p/5278745.html
Copyright © 2011-2022 走看看