I am looking to add an event to a class, and I am using the following answer from stackexchange as a base:
https://stackoverflow.com/questions/85137/how-to-add-an-event-to-a-class
The answer example registers the event every time the frog object jumps.
- public event EventHandler Jump;
- public void OnJump()
- {
- EventHandler handler = Jump;
- if (null != handler)
- handler(this, EventArgs.Empty);
- }
- Frog frog = new Frog();
- frog.Jump += new EventHandler(yourMethod);
- private void yourMethod(object s, EventArgs e)
- {
- Console.WriteLine("Frog has Jumped!");
- }
Now this is fine for non-static methods, but the problem is I have a static method in my class, so the "this" keyword won't work. Here is my version of the code:
-
- public event EventHandler Triggered;
- public static void Trigger()
- {
- EventHandler h = Triggered;
- if (h != null)
- h(this, EventArgs.Empty);
- }
-
- MyClass myObj = new MyClass();
- myObj.Trigger += new EventHandler(TakeAction);
-
- private void TakeAction(object o, EventArgs e)
- {
- Console.WriteLine("We made it.");
- }
"this" in line 7 cannot be used due to the static nature of the funciton. How can I modify this code so that it allows this event to be properly registered.