共用方式為


判斷物件類型 (Visual Basic)

泛型物件變數(也就是您宣告為 Object的變數)可以保存任何類別的物件。 使用 類型的 Object變數時,您可能需要根據 對象的類別採取不同的動作;例如,某些物件可能不支援特定的屬性或方法。 Visual Basic 提供兩種方法來判斷物件類型儲存在物件變數中:函 TypeName 式和 TypeOf...Is 運算符。

TypeName 和 TypeOf...是

TypeName 式會傳回字串,當您需要儲存或顯示對象的類別名稱時,這是最佳選擇,如下列代碼段所示:

Dim Ctrl As Control = New TextBox
MsgBox(TypeName(Ctrl))

運算符 TypeOf...Is 是測試物件類型的最佳選擇,因為它比使用 TypeName的對等字串比較快得多。 以下代碼片段在 TypeOf...Is 語句中使用了 If...Then...Else

If TypeOf Ctrl Is Button Then
    MsgBox("The control is a button.")
End If

在這裡必須小心。 如果物件是特定型別,或衍生自特定型別,則 TypeOf...Is 運算符會 True 傳回 。 您使用 Visual Basic 所做的幾乎所有事情都涉及物件,其中包括一些通常不被視為物件的元素,例如字串和整數。 這些物件衍生自Object,並從中繼承方法。 當傳遞 Integer 並使用 Object 進行評估時,TypeOf...Is 運算符會返回 True。 下列範例報告參數 InParam 同時具有 ObjectInteger 的功能。

Sub CheckType(ByVal InParam As Object)
    ' Both If statements evaluate to True when an
    ' Integer is passed to this procedure.
    If TypeOf InParam Is Object Then
        MsgBox("InParam is an Object")
    End If
    If TypeOf InParam Is Integer Then
        MsgBox("InParam is an Integer")
    End If
End Sub

下列範例同時使用 TypeOf...IsTypeName 來判斷在參數 Ctrl 中傳遞給它的物件類型。 程式 TestObject 會呼叫 ShowType 三種不同類型的控制件。

執行範例

  1. 建立新的 Windows 應用程式專案,並將 Button 控制項、CheckBox 控制項和 RadioButton 控制項新增至表單。

  2. 從表單上的按鈕呼叫 TestObject 程式。

  3. 將下列程式代碼新增至表單:

    Sub ShowType(ByVal Ctrl As Object)
        'Use the TypeName function to display the class name as text.
        MsgBox(TypeName(Ctrl))
        'Use the TypeOf function to determine the object's type.
        If TypeOf Ctrl Is Button Then
            MsgBox("The control is a button.")
        ElseIf TypeOf Ctrl Is CheckBox Then
            MsgBox("The control is a check box.")
        Else
            MsgBox("The object is some other type of control.")
        End If
    End Sub
    
    Protected Sub TestObject()
        'Test the ShowType procedure with three kinds of objects.
        ShowType(Me.Button1)
        ShowType(Me.CheckBox1)
        ShowType(Me.RadioButton1)
    End Sub
    

另請參閱