15 Сентябрь
Microsoft

Event

Пример своего события.

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Stock stock = new Stock();
  6. stock.Price = 27.51M;
  7. stock.PriceChanged += stock_PriceChanged;
  8. stock.Price = 40.00M;
  9. Console.ReadKey();
  10. }
  11.  
  12. static void stock_PriceChanged(object sender, PriceChangedEventArgs e)
  13. {
  14. if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
  15. Console.WriteLine("Alert, 10% stock price increase!");
  16. }
  17. }
  18. public class PriceChangedEventArgs:EventArgs
  19. {
  20. public readonly decimal LastPrice;
  21. public readonly decimal NewPrice;
  22. public PriceChangedEventArgs(decimal lastPrice,decimal newPrice)
  23. {
  24. LastPrice = lastPrice;
  25. NewPrice = newPrice;
  26. }
  27. }
  28. public class Stock
  29. {
  30. decimal price;
  31. public decimal Price
  32. {
  33. get { return price; }
  34. set
  35. {
  36. if (price == value) return;
  37. decimal oldPrice = price;
  38. price = value;
  39. OnPriceChanged(new PriceChangedEventArgs(oldPrice, price));
  40. }
  41. }
  42. public event EventHandler<PriceChangedEventArgs> PriceChanged;
  43. protected virtual void OnPriceChanged(PriceChangedEventArgs e)
  44. {
  45. if (PriceChanged != null) PriceChanged(this, e);
  46. }
  47. }

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Stock stock = new Stock();
  6. stock.PriceChanged += stock_PriceChanged;
  7. stock.Price = 10;
  8. }
  9.  
  10. static void stock_PriceChanged(object sender, EventArgs e)
  11. {
  12. Console.WriteLine("Event! Price changed!");
  13. Console.ReadKey();
  14. }
  15. }
  16. public class Stock
  17. {
  18. public event EventHandler PriceChanged;
  19. protected virtual void OnPriceChaged(EventArgs e)
  20. {
  21. if(PriceChanged!=null)PriceChanged(this,e);
  22. }
  23. decimal price;
  24. public decimal Price
  25. {
  26. get { return price; }
  27. set
  28. {
  29. if (price == value) return;
  30. price = value;
  31. OnPriceChaged(EventArgs.Empty);
  32. }
  33. }
  34. }

Коментарии


Оставить коментарий