我是Reactive Extension的新手,不幸的是我们使用VB.NET,因此我在将C#示例转换为VB.NET时遇到了一些麻烦。
我试图创建一个简单的ObservableCollection(String)并订阅它。无论何时将字符串添加到集合中,我都想将其写入控制台
我试图将这个例子翻译成VB.NET并遇到麻烦。
var x = Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
handler => (sender, e) => handler(sender, e),
handler => theList.CollectionChanged += handler,
handler => theList.CollectionChanged -= handler);
}
我已经走到了这一步,但无法让它发挥作用,我确信它很简单,但我是新手。
Dim changes = Observable.FromEventPattern(Of System.Collections.Specialized.NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs) _
(Function(handler) Function(sender, args) handler(sender, args), _
Function(handler) AddHandler theList.CollectionChanged, AddressOf handler, _
Function(handler) RemoveHandler theList.CollectionChanged, AddressOf handler)
感谢@Gideon Engelberth帮助我删除了不需要的AddressOf
这编译好了:
Dim changes = Observable.FromEventPattern(Of
System.Collections.Specialized.NotifyCollectionChangedEventHandler, _
NotifyCollectionChangedEventArgs) _
(Function(handler) Sub(sender, args) handler(sender, args), _
Sub(handler) AddHandler theList.CollectionChanged, handler, _
Sub(handler) RemoveHandler theList.CollectionChanged, handler)
答案 0 :(得分:3)
根据要求,我通常喜欢这样:
Dim c As New ObservableCollection(Of String)
Dim obs = Observable.FromEventPattern(Of NotifyCollectionChangedEventHandler,
NotifyCollectionChangedEventArgs)(
Sub(h) AddHandler c.CollectionChanged, h,
Sub(h) RemoveHandler c.CollectionChanged, h)
由于h
已经是委托变量,因此您不需要AddressOf运算符。
答案 1 :(得分:0)
AddHandler
和RemoveHandler
来电不会返回值,因此您无法将其与Function
一起使用。尝试使用Sub
代替最后两个参数。
Dim changes = Observable.FromEventPattern(Of System.Collections.Specialized.NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs) _
(Function(handler) Function(sender, args) handler(sender, args), _
Sub(handler) AddHandler theList.CollectionChanged, AddressOf handler, _
Sub(handler) RemoveHandler theList.CollectionChanged, AddressOf handler)