Programmatically triggering an event?

How can I call this method programmatically? If I just do KillZombies (), it says that I don’t have the right parameters, but I don’t know which parameters to specify when I just use the code ...

public static void KillZombies(object source, ElapsedEventArgs e) { Zombies.Kill(); } 
+7
c # events
source share
6 answers

You tried:

 KillZombies(null, null); 

Perhaps reorganize your design:

 public static void KillZombies(object source, ElapsedEventArgs e) { //more code specific to this event, logging, whathaveyou. KillSomeZombies(); } public static void KillSomeZombies() { Zombies.Kill(); } //elsewhere in your class: KillSomeZombies(); 
+6
source share
 KillZombies(null, null); 

However, I would question the good design.

+3
source share

You will have to create parameters and pass them too. Why not just call the function directly by placing it in another function available for other classes to call? This will allow for a more accurate design.

i.e.

 internal void MakeZombiesKill() { Zombies.Kill(); } 

?

+3
source share

Your method signature requires two arguments. You cannot just call KillZombies (), you will need to pass the correct arguments to the method.

 KillZombies(source, e); 

If you don't have a source or e, you can just pass null.

 KillZombies(null, null); 
+1
source share

Usually you use an object inside which you call the method as a source (or null if static). And set ElapsedEventArgs to something relevant to the method. For ElapsedEventArgs, it would be something like this: new ElapsedEventArgs() { SignalTime = DateTime.Now}

 KillZombies(this, new ElapsedEventArgs() { SignalTime = DateTime.Now}); 

Unless you really use the source or e inside the method, you can call it null arguments.

 KillZombies(null, null); 
0
source share

From a technical point of view, you should separate the task from the inside of the event handler and have an event handler that calls the method containing the code you want to run, so you can call this code without disabling the event handler. However, if you want to programmatically disable the event handler:

 KillZombies(this, new ElapsedEventArgs()) 

I will, however, break it as a commonly used best practice ...

0
source share

All Articles