开发者

Calling an event handler manually [duplicate]

This question already has answers here: 开发者_如何学JAVAC#: is calling an event handler explicitly really "a good thing to do"? (7 answers) Closed 9 years ago.

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.
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜