For EventHandler usage, EventHandler
That is, the use of delegation and events. I used it, but I didn't know much about it. Now I will fill in the pitfalls left in the past.
EventHandler and EventHandler <TEventArg> are two delegates defined in. net Framework.
From the definition, the latter receives the TEventArgs parameter in the form of generics, which can be a subclass inherited from EventArgs;
// Summary: // indicates the method used to process events that do not contain event data. //// Parameter: // sender: // event source. //// E: // System. EventArgs that does not contain any event data. [Serializable] [ComVisible (true)] public delegate void EventHandler (object sender, EventArgs e); // Summary: // indicates the method to process the event. //// Parameter: // sender: // event source. //// E: // a System. EventArgs containing event data. //// Type parameter: // TEventArgs: // type of event data generated by the event. [Serializable] public delegate void EventHandler <TEventArgs> (object sender, TEventArgs e );
The default System. EventArgs does not contain parameters, but we can add the required data to the subclass by inheritance.
public class MyEventArgs : EventArgs { public string message { get; set; } public MyEventArgs(string mess) { message = mess; } }
In the preceding example, the class MyEventArgs inherits from System. EventArgs and defines a message attribute of the string type for receiving data.
Use the MyEventArgs class in specific examples
Public class DoTest {public DoTest () {}// defines the event public event EventHandler <MyEventArgs> DoWork; public void Begin (string val) {if (DoWork! = Null) {MyEventArgs e = new MyEventArgs (val); DoWork (this, e );}}}
class Program { static void Main(string[] args) { DoTest dos = new DoTest(); dos.DoWork += (s, e) => { Console.WriteLine(e.message); }; dos.Begin("1"); dos.Begin("2"); dos.Begin("3"); dos.Begin("4"); } }
Dos. DoWork registers an anonymous function, which outputs a message indicating the parameter value.
When the Begin ("1") function is called, 1 is displayed. At this time, the passed parameters can be obtained through e. message.