-
Notifications
You must be signed in to change notification settings - Fork 1
/
SimpleEvent.cs
70 lines (57 loc) · 1.75 KB
/
SimpleEvent.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
public class Program
{
public static void Main()
{
MyEventClass myEvent = new MyEventClass();
MyHandlerClass myHandler = new MyHandlerClass(myEvent);
myEvent.InvokeEvent("Foo");
myEvent.InvokeEvent("Bar");
return;
}
}
/// <summary>
/// This class is responsible for firing the event.
/// </summary>
public class MyEventClass
{
public delegate void MyEventHandlerDelegate(object sender, MyEventArgs fe);
// Public event based on the delegate.
public event MyEventHandlerDelegate MyEvent;
public void InvokeEvent(string description)
{
// Create the EventArgs so parameters can be passed.
MyEventArgs eventArgs = new MyEventArgs(description);
MyEvent(this, eventArgs);
}
}
/// <summary>
/// This class is responsible for handling the event after it's fired.
/// </summary>
public class MyHandlerClass
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="myEventClass">The class that will fire the event.</param>
public MyHandlerClass(MyEventClass myEventClass)
{
// Configure a delegate with the function that will be executed when the event is raised.
myEventClass.MyEvent += new MyEventClass.MyEventHandlerDelegate(RespondToTheEventBeingRaised);
}
void RespondToTheEventBeingRaised(object sender, MyEventArgs fe)
{
Console.WriteLine("Sender Class: {0}, Description: {1}", sender.ToString(), fe.description);
}
}
/// <summary>
/// This class is responsible for passing information to the handler class.
/// </summary>
public class MyEventArgs : EventArgs
{
public string description;
public MyEventArgs(string description)
{
this.description = description;
}
}