using System; using System.Collections.Generic; //--------------------------------------------------------- public class MyEventArgs : EventArgs { private string msg; public MyEventArgs(string messageData) { msg = messageData; } public string Message { get { return msg; } set { msg = value; } } } //--------------------------------------------------------- public class HasEvent { // Declare an event of delegate type EventHandler of // MyEventArgs. public event EventHandler<MyEventArgs> SampleEvent; public void DemoEvent(string val) { // Copy to a temporary variable to be thread-safe. EventHandler<MyEventArgs> temp = SampleEvent; if (temp != null) temp(this, new MyEventArgs(val)); } } //--------------------------------------------------------- public class Example { private static System.Windows.Controls.TextBlock outputBlock; public static void Demo(System.Windows.Controls.TextBlock outputBlock) { Example.outputBlock = outputBlock; HasEvent he = new HasEvent(); he.SampleEvent += new EventHandler<MyEventArgs>(ExampleEventHandler); he.DemoEvent("Hey there, Bruce!"); he.DemoEvent("How are you today?"); he.DemoEvent("I'm pretty good."); he.DemoEvent("Thanks for asking!"); } private static void ExampleEventHandler(object src, MyEventArgs mea) { outputBlock.Text += mea.Message + "/n"; } } //--------------------------------------------------------- /* This example produces the following results: Hey there, Bruce! How are you today? I'm pretty good. Thanks for asking! */
EventHandler 的用法
最新推荐文章于 2024-08-31 09:00:52 发布