我正在查看this博客,並且我正在嘗試將該片段翻譯爲VB。需要幫助翻譯C#到VB
我遇到困難,這條線:
NotifyCollectionChangedEventHandler handlers = this.CollectionChanged;
注:CollectionChanged就是這樣的一個事件(「本」是ObservableCollection<T>
的覆蓋)。
我正在查看this博客,並且我正在嘗試將該片段翻譯爲VB。需要幫助翻譯C#到VB
我遇到困難,這條線:
NotifyCollectionChangedEventHandler handlers = this.CollectionChanged;
注:CollectionChanged就是這樣的一個事件(「本」是ObservableCollection<T>
的覆蓋)。
要提高事件,OnCollectionChanged
應該可以正常工作。如果你想查詢它,你必須獲得更多的虐待和使用反射(對不起,例如是C#,但應該是幾乎相同的 - 我沒有使用任何特定語言的功能在這裏):
NotifyCollectionChangedEventHandler handler = (NotifyCollectionChangedEventHandler)
typeof(ObservableCollection<T>)
.GetField("CollectionChanged", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(this);
等瞧;處理程序或處理程序(通過GetInvocationList()
)。
所以基本上在你的榜樣(關於該職位),用途:
Protected Overrides Sub OnCollectionChanged(e As NotifyCollectionChangedEventArgs)
If e.Action = NotifyCollectionChangedAction.Add AndAlso e.NewItems.Count > 1 Then
Dim handler As NotifyCollectionChangedEventHandler = GetType(ObservableCollection(Of T)).GetField("CollectionChanged", BindingFlags.Instance Or BindingFlags.NonPublic).GetValue(Me)
For Each invocation In handler.GetInvocationList
If TypeOf invocation.Target Is ICollectionView Then
DirectCast(invocation.Target, ICollectionView).Refresh()
Else
MyBase.OnCollectionChanged(e)
End If
Next
Else
MyBase.OnCollectionChanged(e)
End If
End Sub
從字面上看,它應該像
Dim handlers As NotifyCollectionChangedEventHandler = AddressOf Me.CollectionChanged
(不能告訴,因爲我不知道確切的類型)
但請注意,您在使用提高在VB事件RaiseEvent
這僅'CollectionChanged'是用戶,而不是事件處理程序(它可能是),但在這種情況下,您的作品第二句適用。 – 2010-02-01 19:20:55
它根本不起作用,一年前我嘗試過。 AddressOf只需要一個方法名稱。 – Shimmy 2010-02-01 19:29:59
@Shimmy:給出你的信息,這是一個有效的猜測。 'AddressOf'在這個確切的上下文中起作用。沒有其他直接翻譯你想要的。 – 2010-02-01 19:33:01
杜。在已經終於看到和閱讀的博客張貼您鏈接,這裏的答案:
在VB中,你需要聲明一個自定義事件覆蓋RaiseEvent
機制。在最簡單的情況下,這看起來是這樣的:
Private m_MyEvent As EventHandler
Public Custom Event MyEvent As EventHandler
AddHandler(ByVal value as EventHandler)
m_MyEvent = [Delegate].Combine(m_MyEvent, value)
End AddHandler
RemoveHandler(ByVal value as EventHandler)
m_MyEvent = [Delegate].Remove(m_MyEvent, value)
End RemoveHandler
RaiseEvent(sender as Object, e as EventArgs)
Dim handler = m_MyEvent
If handler IsNot Nothing Then
handler(sender, e)
End If
End RaiseEvent
End Event
在你的情況下,RaiseEvent
例程是稍微有點複雜,以反映額外的邏輯,但要點是一樣的。
@Shimmy:我回滾了你的編輯;它實際上引入了一個令人討厭的多線程錯誤。複製事件處理程序**是重要的! (和'Shadows'在那裏沒有任何地方。) – 2010-02-01 20:12:17
我怎樣才能進入基地事件呢? – Shimmy 2010-02-01 20:21:04
@Shimmy:你不能。無論出於何種原因,任何類都不能直接訪問其基類事件。 .NET只是不允許。 – 2010-02-01 21:05:29
@Mark,你是贏家,大好時光! – Shimmy 2010-02-01 22:11:05