重大变更破坏了 Rx 样本
Rx Wiki 的 101 个 Rx 示例中的一些示例实际上不再起作用。我认为这是因为我拥有最新的 Rx 版本(1.0.10621.2),但我想确认并看看如何让它们工作。
例如,以下示例代码不起作用:
class ObserveEvent_Generic
{
public class SomeEventArgs : EventArgs { }
public static event EventHandler<SomeEventArgs> GenericEvent;
static void Main()
{
// To consume GenericEvent as an IObservable:
IObservable<IEvent<SomeEventArgs>> eventAsObservable = Observable.FromEvent<SomeEventArgs>(
ev => GenericEvent += ev,
ev => GenericEvent -= ev);
}
}
缺少 IEvent 并且“ev => GenericEvent += ev”导致“无法将类型 System.Action
隐式转换为 <代码>System.EventHandler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,您有几种选择。第一个是提供与标准 EventHandler 模式匹配的委托(生成的 Observable 的类型为 IObservable)。请注意,我提供的 lamda 接受“
o
”(“发送者”),但未使用此参数:特别是在您的情况下(静态事件...哎呀!),我将不愿信任取消订阅会真正正确地清理,并且根据使用情况,您可能最终会出现严重的内存泄漏。作为替代方案,您可以指定委托类型。注意这里
FromEvent
的额外泛型参数另一种替代方案是将源/发送者对象的处理移至观察者(使可观察类型为
IObservable>) 是使用
FromEventPattern
方法。我在某些构建中使用此方法遇到了一些麻烦,因此您的情况可能会有所不同,但这是替代方案:希望这会有所帮助。
You have a few options in this case. The first is to provide a delegate that matches the standard EventHandler pattern (the resulting Observable is of type
IObservable<SomeEventArgs>
). Notice the lamda I provided accepts "o
" (the "sender"), but this param is not used:Especially in your situation (static event... yikes!), I would be reticent to trust that the unsubscribe would truly cleanup properly and you might end up with a nasty memory leak depending on usage. As an alternative, you can specify the delegate type. Notice here the extra generic parameter to
FromEvent
One more alternative that moves the handling of the source/sender object to the Observer (making the observable of type
IObservable<EventPattern<SomeEventArgs>>
) is to use theFromEventPattern
method. I've had a little trouble with this method in some builds, so your mileage may vary, but here is that alternative:Hopefully this helps a bit.
FromEvent
扩展方法已重命名为FromEventPattern
,因此执行此操作,101 个示例应该可以工作。令人困惑的是,为非标准事件创建了新的
FromEvent
重载。他们应该将其命名为FromEventAction
但他们没有。The
FromEvent
extension method has been renamed toFromEventPattern
so do this and the 101 samples should work.The confusing thing is that a new
FromEvent
overload was created for non-standard events. They should have called itFromEventAction
but they didn't.许多示例来自 Jesse Liberty 和 Paul Betts 的《Programming Reactive Extensions and LINQ》书坏了:( :( 太伤心了...
A lot of samples from Programming Reactive Extensions and LINQ by Jesse Liberty and Paul Betts book is broken :( :( It's so sad...