【问题标题】:How do I dynamically get an object type and cast to it?如何动态获取对象类型并转换为它?
【发布时间】:2021-06-23 22:43:20
【问题描述】:

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

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 

编辑

据我所知,ToolStripItem (ToolStripButton) 不是Control,所以我不能在这种情况下使用List(Of Control)。当我第一次使用控件列表时,工具条项目不包括在内。这是我第一次在应用程序中使用ToolStrip,所以直到现在我都没有理由不使用List(Of Control)

【问题讨论】:

  • Dim MyObjectsAs New List(Of Control)?
  • 在大多数情况下,我只使用List(Of Control),但是,ToolStripButton 不会包含在列表中。所以我的解决方法是创建一个List(Of Object) 并将所有内容都包含在其中。 @GSerg

标签: vb.net directcast


【解决方案1】:

所有控件都派生自Control。因此,不要使用Object 类型,而是使用ControlControl 拥有这些控件的大部分成员,例如 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

FindControlsRecursive 中也使用Control

见:


原来你有一些组件不是控件。但是您仍然可以将所有控件投射到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

请注意,ToolStripItem 包括 ToolStripButtonToolStripControlHostToolStripDropDownItemToolStripLabelToolStripSeparator,因为所有这些组件都派生自 ToolStripItem。您可以在 Visual Studio 的对象浏览器中看到:

MenuStrip 是一个Control。因此,这两种情况应该涵盖您的大部分控件和组件。如果您发现此处未涵盖的另一个组件,请搜索其具有Click 事件的最小派生基类型,以便新案例涵盖尽可能多的组件。

【讨论】:

  • 我知道 ControlControls 的派生词,但我相信 ToolStripButtonToolStripItem 不是控件,因此它们不会被包含在 List(Of Control )。我仍然需要将一些对象包含在列表中。如果 toolstripitems 是一个控件,那么无论出于何种原因,它都不会包含在我的控件列表中
  • 谢谢奥利维尔!
猜你喜欢
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 2018-10-13
相关资源
最近更新 更多