自检代表:避免调用之前检查空?代表

由网友(余生爱自己)分享简介:有没有聪明的方式来避免调用它在一个通用的方法之前测试的无效对事件的详细程度?它看起来很明显,如果我叫一个代表,我希望它被分配。(如果我的真的的希望/需要测试其无效我可能最终明确地做到这一点,但把这个测试系统是一种冗长乏味。)公共委托无效ResetTradesDelegate();公共ResetTradesDeleg...

有没有聪明的方式来避免调用它在一个通用的方法之前测试的无效对事件的详细程度?它看起来很明显,如果我叫一个代表,我希望它被分配。 (如果我的真的的希望/需要测试其无效我可能最终明确地做到这一点,但把这个测试系统是一种冗长乏味。)

 公共委托无效ResetTradesDelegate();
公共ResetTradesDelegate ResetTradesEvents;

公共无效OnSessionRxAdmMessage(IVfxFixAppSession会议,FixMessage MSG)
{
    如果(ResetTradesEvent!= NULL)//<  - 有没有任何的方式不明确写入本次测试为每个代表?
       ResetTradesEvent();
}
 

解决方案

 公共事件的EventHandler NoDataEventHandler =委托{};
 

在这种方式声明的事件意味着它永远不会为空。它总是在最低限度,有一个空操作的事件处理程序挂钩。

第二部分 高级

在你的情况,很可能

 公共事件ResetTradesDelegate ResetTradesEvents =委托{};
 

触发一个事件总是将不得不与它相关的竞争条件。你要么去冒险尝试调用委托时,它的空,或者调用委托的事件已经脱钩之后。埃里克利珀关于这一主题的此处。上面仍是技术从所述第二类型的竞争条件患有,因此事件处理程序必须是健壮到被称为事件已被脱钩后

Is there any smart way to avoid the verbosity of testing the nullity on an event before calling it in a generic way ? It looks obvious that if I call a delegate, I want it to be assigned. (If I Really want/need to test its nullity I could eventually do it explicitly, but putting this test systematically is kind of tedious and verbose.)

public delegate void ResetTradesDelegate();
public ResetTradesDelegate ResetTradesEvents;

public void OnSessionRxAdmMessage(IVfxFixAppSession session, FixMessage msg)
{    
    if (ResetTradesEvent != null)  //<-- Is there "any" a way not to write this test explicitly for each delegate ?
       ResetTradesEvent();
}

解决方案

public event EventHandler NoDataEventHandler = delegate{};

Declaring an event in this way means it will never be null. It will always, at a minimum, have a single no-op event handler hooked up.

In your case, probably

public event ResetTradesDelegate ResetTradesEvents = delegate{};

Firing an event is always going to have a race condition associated with it. You're either going to risk trying to call a delegate when it's null, or calling a delegate after the event has been unhooked. Eric Lippert wrote a pretty comprehensive post on this topic here. The technique above still suffers from the second type of race condition, so the event handlers need to be robust to being called after the event has been unhooked.

阅读全文

相关推荐

最新文章