《C#進階編程》委託、事件的範例程式碼

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   2014   

運行結果:

 

Program.cs

 1 using System; 2  3 namespace Wrox.ProCSharp.Delegates 4 { 5     class Program 6     { 7         static void Main() 8         { 9             var dealer = new CarDealer();10 11             var michael = new Consumer("Michael");12             dealer.NewCarInfo += michael.NewCarIsHere;13 14             dealer.NewCar("Mercedes");15 16             var nick = new Consumer("Nick");17             dealer.NewCarInfo += nick.NewCarIsHere;18 19             dealer.NewCar("Ferrari");20 21             dealer.NewCarInfo -= michael.NewCarIsHere;22 23             dealer.NewCar("Toyota");24 25             Console.Read();26         }27     }28 }

 

CarDealer.cs

 1 using System; 2  3 namespace Wrox.ProCSharp.Delegates 4 { 5     public class CarInfoEventArgs : EventArgs 6     { 7         public CarInfoEventArgs(string car) 8         { 9             this.Car = car;10         }11 12         public string Car { get; private set; }13     }14 15     public class CarDealer16     {17         public event EventHandler<CarInfoEventArgs> NewCarInfo;18 19         public void NewCar(string car)20         {21             Console.WriteLine("CarDealer, new car {0}", car);22             if (NewCarInfo != null)23             {24                 NewCarInfo(this, new CarInfoEventArgs(car));25             }26         }27     }28 }

 

Consumer.cs

 1 using System; 2  3 namespace Wrox.ProCSharp.Delegates 4 { 5     public class Consumer 6     { 7         private string name; 8  9         public Consumer(string name)10         {11             this.name = name;12         }13 14         public void NewCarIsHere(object sender, CarInfoEventArgs e)15         {16             Console.WriteLine("{0}: car {1} is new", name, e.Car);17         }18     }19 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.