如何动态分配对象类型?



我正在尝试遍历面板中的所有控件。一些控件作为我创建的类。在这些类中,我希望在删除对象时运行子例程。所以我正在尝试创建一个可用于运行该例程的临时对象。

For Each window As Control In main_window.Controls
If window.Handle = hdl Then
Dim temp_window as window.getType()
temp_window.close_me()
main_window.Controls.Remove(window)
End If
Next 

但是,不允许使用 getType 赋值。

我怎样才能做到这一点?

Object.GetType不是你想要的,它返回对象的Type实例,其中包含该类型的元数据,通常用于反射。

您想要的实际类型是什么?它必须有一个close_me的方法。您可以使用OfType

Dim windowsToClose = main_window.Controls.OfType(Of YourWindowType)().
Where(Function(w) w.Handle = hdl).
ToArray()
For Each window In windowsToClose 
window.close_me()
main_window.Controls.Remove(window)
Next 

For Each不起作用还有其他原因:在枚举集合时,无法从集合中删除项。上面的方法将要删除的窗口存储在数组中。

执行此操作的正确方法是使用控件Inherit的基类或控件Implement的接口,close_me基或接口。 然后,您可以将Controls的每个成员TryCast到基接口或接口,如果成功,则对其调用close_me。 如果你使用基类方法,你可能希望把它抽象化(MustInherit(,然后close_meMustOverride,这取决于每个派生类型的行为是否应该不同。

例如,假设您使用ICloseable

Interface ICloseable
Sub close_me()
End Interface
'...
For Each window As Control In main_window.Controls
If window.Handle = hdl Then
Dim asCloseable = TryCast(window, ICloseable)
If asCloseable IsNot Nothing Then
asCloseable.close_me()
EndIf
EndIf
Next

最新更新