Calling an event handler manually [duplicate]
I have an event handler method that's called directly as a standard method. That is, it's not only called when my event occurs but also just as a private method.
UtilStk.StkRoot.OnStkObjectAdded += new
IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);
private void TallyScenarioObjects(object sender)
{
...
}
Is it suitable to pass a null argument when calling this handler directly?
TallyScenarioObjects(null);
Just encapsulate the common logic into another method that can be called from your event handler:
UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);
private void TallyScenarioObjects(object sender)
{
DoStuff();
}
private void DoStuff() { ... }
private void AnotherMethod()
{
DoStuff();
}
That said, your handler is a method, there's nothing special about it, so you could always dummy up arguments and call it directly. I wouldn't go that route though.
Yes that would work, but it would be better practice to have a 2nd method that could be called directly or from the event handler:
UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);
private void TallyScenarioObjects(object sender)
{
DoTally(....);
}
private void DoTally(....)
{
}
If nothing else you won't confuse other developers who won't be expecting to see an event handler called that way.
I agree with the rest. Have your event call a method. Then you can invoke that method from wherever you'd like.
UtilStk.StkRoot.OnStkObjectAdded += new IAgStkObjectRootEvents_OnStkObjectAddedEventHandler(TallyScenarioObjects);
private void TallyScenarioObjects(object sender)
{
MyMethod();
}
private void MyMethod()
{
//Code here.
}
精彩评论