3

我是 Reactive Extension 的新手,不幸的是我们使用的是 VB.NET,所以我在将 C# 示例转换为 VB.NET 时遇到了一些麻烦。
我正在尝试创建一个简单的 ObservableCollection(of 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)
4

2 回答 2

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 运算符。

于 2012-08-10T23:29:31.803 回答
0

AddHandlerandRemoveHandler调用不返回值,因此您不能将它们与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)
于 2012-08-10T20:09:43.840 回答