如何动态获取对象类型并强制转换为对象类型?

How do I dynamically get an object type and cast to it?

提问人:John89 提问时间:6/16/2021 最后编辑:John89 更新时间:6/23/2021 访问量:247

问:

如何获取对象类型,以便可以直接强制转换为对象?这是我想执行的理想方法:

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。当我第一次使用控件列表时,工具条项不包括在内。这是我第一次在应用程序中使用,所以直到现在我才有理由不使用。ToolStripItemControlList(Of Control)ToolStripList(Of Control)

vb.net Directcast

评论

0赞 GSerg 6/16/2021
Dim MyObjectsAs New List(Of Control)?
0赞 John89 6/16/2021
在大多数情况下,我只是使用 ,但是,不会包含在列表中。所以我的方法是制作一个并包含所有内容。@GSergList(Of Control)ToolStripButtonList(Of Object)

答:

4赞 Olivier Jacot-Descombes 6/16/2021 #1

所有控件都派生自 。因此,不要使用类型 use . 具有这些控件的大多数成员,例如事件。ControlObjectControlControlClick

Dim myControls As New List(Of Control)
For Each ctrl As Control In _
  GlobalFunctions.GeneralFunctions.FindControlsRecursive(myControls, Form)

    AddHandler ctrl.Click, AddressOf GotFocus
Next

也使用。ControlFindControlsRecursive

看:


事实证明,您有一些组件不是控件。但是,您仍然可以将所有控件强制转换为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:ToolStripItemToolStripButtonToolStripControlHostToolStripDropDownItemToolStripLabelToolStripSeparatorToolStripItementer image description here

MenuStrip是一个 .因此,这两种情况应涵盖大多数控件和组件。如果发现此处未涵盖的其他组件,请搜索其以事件为特色的最少派生基类型,以便新事例涵盖尽可能多的组件。ControlClick

评论

0赞 John89 6/16/2021
我知道 a 是 的派生物,但我相信并且不是控件,因此它们不会包含在 List(Of Control) 中。我仍然需要在列表中包含一些对象。如果 toolstripitems 是一个控件,那么无论出于何种原因,它都不会包含在我的控件列表中ControlControlsToolStripButtonToolStripItem