gpt4 book ai didi

c# - 自测委托(delegate) : avoid checking for null before invocation?

转载 作者:太空狗 更新时间:2023-10-29 18:08:34 27 4
gpt4 key购买 nike

有什么聪明的方法可以避免在以通用方式调用事件之前测试事件的无效性的冗长吗?很明显,如果我调用一个委托(delegate),我希望它被分配。
(如果我真的想要/需要测试它的无效性,我最终可以明确地做它,但是系统地进行这个测试有点乏味和冗长。)

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{};

以这种方式声明一个事件意味着它永远不会为空。它将始终至少连接一个无操作事件处理程序。

在你的情况下,可能

public event ResetTradesDelegate ResetTradesEvents = delegate{};

触发一个事件总是会有一个与之相关的竞争条件。您要么冒险尝试在委托(delegate)为 null 时调用委托(delegate),要么在事件解除后调用委托(delegate)。 Eric Lippert 就此主题写了一篇非常全面的文章 here .上述技术仍然存在第二种类型的竞争条件,因此事件处理程序需要稳健,以便在事件解除后被调用。

关于c# - 自测委托(delegate) : avoid checking for null before invocation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459813/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com