提问人:John89 提问时间:6/16/2021 最后编辑:John89 更新时间:6/23/2021 访问量:247
如何动态获取对象类型并强制转换为对象类型?
How do I dynamically get an object type and cast to it?
问:
如何获取对象类型,以便可以直接强制转换为对象?这是我想执行的理想方法:
Dim MyObjects As New List(Of Object)
For Each O As Object In GlobalFunctions.GeneralFunctions.FindControlsRecursive(MyObjects, Form)
Select Case True
Case TypeOf O Is MenuStrip Or TypeOf O Is ToolStripButton Or TypeOf O Is Panel Or TypeOf O Is Label Or TypeOf O Is ToolStripSeparator
AddHandler DirectCast(O, O.GetType).Click, AddressOf GotFocus
End Select
Next
我正在尝试使代码更有效率,这样我就不必直接转换为指定的对象类型。前任。:
Dim MyObjectsAs New List(Of Object)
For Each O As Object In GlobalFunctions.GeneralFunctions.FindControlsRecursive(MyObjects, Form)
Select Case True
Case TypeOf O Is MenuStrip
AddHandler DirectCast(O, MenuStrip).Click, AddressOf GotFocus
Case TypeOf O Is Panel
AddHandler DirectCast(O, Panel).Click, AddressOf GotFocus
Case TypeOf O Is ToolStripButton
AddHandler DirectCast(O, ToolStripButton).Click, AddressOf GotFocus
Etc...
End Select
Next
编辑
据我所知,(ToolStripButton)不是,所以我不能在这种情况下使用a。当我第一次使用控件列表时,工具条项不包括在内。这是我第一次在应用程序中使用,所以直到现在我才有理由不使用。ToolStripItem
Control
List(Of Control)
ToolStrip
List(Of Control)
答:
所有控件都派生自 。因此,不要使用类型 use . 具有这些控件的大多数成员,例如事件。Control
Object
Control
Control
Click
Dim myControls As New List(Of Control)
For Each ctrl As Control In _
GlobalFunctions.GeneralFunctions.FindControlsRecursive(myControls, Form)
AddHandler ctrl.Click, AddressOf GotFocus
Next
也使用。Control
FindControlsRecursive
看:
事实证明,您有一些组件不是控件。但是,您仍然可以将所有控件强制转换为Control
Dim myControls As New List(Of Object)
For Each obj As Object In
GlobalFunctions.GeneralFunctions.FindControlsRecursive(myControls, Form)
Select Case True
Case TypeOf obj Is Control
AddHandler DirectCast(obj, Control).Click, AddressOf GotFocus
Case TypeOf obj Is ToolStripItem
AddHandler DirectCast(obj, ToolStripItem).Click, AddressOf GotFocus
End Select
Next
请注意,包括 、 、 和 ,因为所有这些组件都派生自 。可以在 Visual Studio 的对象浏览器中看到以下内容:You can see this in the Object Browser in Visual Studio:ToolStripItem
ToolStripButton
ToolStripControlHost
ToolStripDropDownItem
ToolStripLabel
ToolStripSeparator
ToolStripItem
MenuStrip
是一个 .因此,这两种情况应涵盖大多数控件和组件。如果发现此处未涵盖的其他组件,请搜索其以事件为特色的最少派生基类型,以便新事例涵盖尽可能多的组件。Control
Click
评论
Control
Controls
ToolStripButton
ToolStripItem
评论
Dim MyObjectsAs New List(Of Control)
?List(Of Control)
ToolStripButton
List(Of Object)