Prism EventAggregator订阅将自己引用为取消订阅的委托

时间:2020-07-11 01:57:45

标签: c# delegates prism eventaggregator

是否可以执行以下操作:

EventHandler handler = null;
handler = (s, args) =>
{
    DoStuff();
    something.SomeEvent -= handler;
};
something.SomeEvent += handler;

使用Prism的EventAggregator? 即

Action subscriber = null;
subscriber = () =>
{
    DoStuff();
    EventAggregator.GetEvent<SomeEvent>().Unsubscribe(subscriber);
};
EventAggregator.GetEvent<SomeEvent>().Subscribe(subscriber);

2 个答案:

答案 0 :(得分:1)

是的,它也可以与Prism的事件汇总器一起使用。归结为比较两个示例中代表是否平等。在匿名方法中引用委托并不特定于事件聚合器。

但是,您应该意识到,使用匿名方法进行这种一次性事件处理是可行的,因为您坚持使用委托实例handlersubscriber,订阅和取消订阅在更复杂的情况下,使用匿名方法进行操作可能会非常具有挑战性。您应该看看这两个问题,以了解委托比较如何用于匿名方法。

作为使用匿名方法的替代方法,您可以使用实例方法或在{em> C#7.0 中引入的local functions,如以下示例所示。

private void AddEventHandler()
{
   // Local method to replace your anonymous method
   void DoStuffAndUnsubscribe()
   {
      DoStuff();
      eventAggregator.GetEvent<SomeEvent>().Unsubscribe(DoStuffAndUnsubscribe);
   }

   eventAggregator.GetEvent<SomeEvent>().Subscribe(DoStuffAndUnsubscribe);
}

@Haukinger指出,最简洁的方法是使用匿名方法捕获事件的订阅令牌的实例,以使用Dispose()取消订阅。

IDisposable subscriptionToken = null;
subscriptionToken = eventAggregator.GetEvent<SomeEvent>().Subscribe(() =>
{
    DoStuff();
    subscriptionToken.Dispose();
});

答案 1 :(得分:1)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="field"> <input type="text" class="input" data-id="1" /><button>+</button> </div>返回一个订阅对象,您可以将其取消订阅:

Subscribe