gpt4 book ai didi

.net - WithEvents LinkedList 是不可能的吗?

转载 作者:行者123 更新时间:2023-12-02 02:34:31 25 4
gpt4 key购买 nike

WithEvents Collection - VB.NET 的最佳方法是什么?

您对下面的代码有任何评论(跳过 Nothing 验证)吗?

问题是当我在 For Each block 中获取 LinkedListNode(Of Foo) 时,我可以设置myNode.Value = something,这是处理程序泄漏...

-在这种情况下,我可以覆盖 FooCollection 的 GetEnumerator 吗?
-不。 :( 原因 NotInheritable Class LinkedListNode(Of T)

Class Foo
Public Event SelectedChanged As EventHandler
End Class

Class FooCollection
Inherits LinkedList(Of Foo)
Public Event SelectedChanged As EventHandler

Protected Overloads Sub AddFirst(ByVal item As Foo)
AddHandler item.SelectedChanged, AddressOf OnSelectedChanged
MyBase.AddFirst(item)
End Sub

Protected Overloads Sub AddLast(ByVal item As Foo)
AddHandler item.SelectedChanged, AddressOf OnSelectedChanged
MyBase.AddLast(item)
End Sub

' ------------------- '

Protected Overloads Sub RemoveFirst()
RemoveHandler MyBase.First.Value.SelectedChanged, _
AddressOf OnSelectedChanged
MyBase.RemoveFirst()
End Sub

Protected Overloads Sub RemoveLast(ByVal item As Foo)
RemoveHandler MyBase.Last.Value.SelectedChanged, _
AddressOf OnSelectedChanged
MyBase.RemoveLast()
End Sub

' ------------------- '

Protected Sub OnSelectedChanged(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent SelectedChanged(sender, e)
End Sub
End Class

最佳答案

主要问题是您无法正确覆盖 GetEnumerator 函数。在这种情况下,我会创建一个不直接从 LinkedList 继承的类,而是只将一个用作私有(private)字段:

Class FooCollection
Implements ICollection(Of Foo)

Private list As New LinkedList(Of Foo)

Public Sub AddFirst(ByVal item As Foo)
AddHandler item.SelectedChanged, AddressOf OnSelectedChanged
list.AddFisrt(item)
End Sub

...

End Class

这将需要更多的编码,因为您需要实现所有功能,而不仅仅是您想要覆盖的功能,但实现是微不足道的。

关于.net - WithEvents LinkedList 是不可能的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2386114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com