开发者

Programmatically triggering an event?

How can I call this method programmatically? If I simple do KillZombies(), it says I don't have the correct parameters, but I don't know what parameters t开发者_运维问答o specify when I'm just using code...

public static void KillZombies(object source, ElapsedEventArgs e)
{
    Zombies.Kill();
}


Have you tried:

KillZombies(null, null);

Perhaps refactor 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();


KillZombies(null, null);

However, I would question whether that's a good design.


You'd have to create the parameters and pass them through too. Why not just call the function directly by putting it in another function that is available for other classes to call? It'll make for much neater design.

i.e.

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

?


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 do not have your source or e, you can simply pass null.

KillZombies(null, null);


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

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

If you don't really use source or e inside the method you can call it with null arguments.

KillZombies(null, null);


Technically speaking, you should be separating out the task from inside the event handler and have the event handler call the method containing the code you want run, this way you can call that code without tripping the event handler. However, if you want to trip the event handler programmatically:

KillZombies(this, new ElapsedEventArgs())

I however would break it out as is a frequently used best practice...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜