我已经开始使用官方初学者指南来玩弄 .NET 的 Reactive Extensions 了,但是很多方法重载对我不起作用(我参考了 System.Reactive)。我不确定这是因为指南已过时还是有其他原因(如果我缺少一些程序集,请告诉我)。这是原始代码和更改后的代码:
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Forms;
namespace RxFormsSandbox
{
class Program
{
static void Main(string[] arguments)
{
var textBox = new TextBox();
var form = new Form { Controls = { textBox } };
// MY CODE (WORKING)
var mouseMoves = Observable.FromEvent<MouseEventHandler, MouseEventArgs>(
handlerAction => (_, args) => handlerAction(args),
handler => form.MouseMove += handler,
handler => form.MouseMove -= handler);
var input = Observable.FromEvent<EventHandler, EventArgs>(
handlerAction => (_, args) => handlerAction(args),
handler => textBox.TextChanged += handler,
handler => textBox.TextChanged -= handler);
var mouseMovesSubscription = mouseMoves.Select(x => x.Location.ToString()).Subscribe(Console.WriteLine);
var inputSubscription = input.Subscribe(x => Console.WriteLine(textBox.Text)); // can I do this without directly accessing 'label' (via sender)
// END OF MY CODE
// ORIGINAL CODE AS PROVIDED IN THE SAMPLE
// var mouseMoves = Observable.FromEvent<MouseEventArgs>(form, "MouseMove");
// var input = Observable.FromEvent<MouseEventArgs>(textBox, "TextChanged");
//
// var mouseMovesSubscription = mouseMoves.Select(x => x.EventArgs.Location.ToString()).Subscribe(Console.WriteLine);
// var inputSubscription = input.Subscribe(x => Console.WriteLine(((TextBox)x.Sender).Text));
// END OF ORIGINAL SAMPLE CODE
using (new CompositeDisposable(mouseMovesSubscription, inputSubscription))
{
Application.Run(form);
}
}
}
}
前提是,方法的签名确实在版本之间发生了变化,有几件事让我对我的解决方案感到困惑,我想问一下是否有更好的方法:
- 我重写的版本明显更长,我认为表达力较差。有没有办法让它更短(理想情况下不引入魔术字符串)?
- input.Subscribe(x => Console.WriteLine(textBox.Text)); 不是很好,因为它引用了外部代码。我想通过“发件人”属性以某种方式访问它。
我的程序集来自 NuGet,它的版本是 1.0.10621.0。