簡體   English   中英

如何動態獲取 object 類型並轉換為它?

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

如何獲得 object 類型以便我可以直接轉換為它? 這是我想執行的理想方法:

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

我試圖使代碼更高效,這樣我就不必直接轉換為指定的 object 類型。 前任。:

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)

所有控件都派生自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

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 的 Object 瀏覽器中看到這一點: 在此處輸入圖像描述

MenuStrip是一個Control 因此,這兩種情況應該涵蓋您的大部分控件和組件。 如果您發現此處未涵蓋的另一個組件,請搜索其具有Click事件的派生最少的基本類型,以便新案例涵蓋盡可能多的組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM