【问题标题】:How to subscribe to TypedEventHandler<T, TArgs> event using IObservable如何使用 IObservable 订阅 TypedEventHandler<T, TArgs> 事件
【发布时间】:2019-09-01 17:09:11
【问题描述】:

我正在尝试以下,

var _connectedAnimation = ConnectedAnimationService.GetForCurrentView().GetAnimation("forwardAnimation");

Observable.FromEvent<TypedEventHandler<ConnectedAnimation, object>, object>(
          handler => _connectedAnimation.Completed += handler,
          handler => _connectedAnimation.Completed -= handler)

但是,当引发事件时,我得到运行时异常

System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
  at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)
  at System.Reactive.ReflectionUtils.CreateDelegate[TDelegate](Object o, MethodInfo method) in D:\a\1\s\Rx.NET\Source\src\System.Reactive\Internal\ReflectionUtils.cs:line 24
  at System.Reactive.Linq.ObservableImpl.FromEvent`2.GetHand

完成的事件定义为

public sealed class ConnectedAnimation : IConnectedAnimation, IConnectedAnimation2, IConnectedAnimation3
{
    /// <summary>Occurs when the animation is finished.</summary>
    public extern event TypedEventHandler<ConnectedAnimation, object> IConnectedAnimation.Completed;
}

【问题讨论】:

    标签: system.reactive


    【解决方案1】:

    由于它不是标准事件,也因为有多个事件参数,我们需要创建一个Tuple。请参阅Rx.Net in Action 中的4.2.3. Events with multiple parameters

    Observable.FromEvent<TypedEventHandler<ConnectedAnimation, object>, Tuple<ConnectedAnimation, object>>(
        rxHandler => (animation, o)=> rxHandler(Tuple.Create(animation,o)),
        handler => _connectedAnimation.Completed += handler,
        handler => _connectedAnimation.Completed -= handler)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多