Nothing (Visual Basic)

代表任何資料型別的預設值。

備註

將 Nothing 指派給某變數,將之設定其所宣告的資料型別之預設值。 如果該型別包含變數成員,皆會設定為自己型別的預設值。 下列範例以純量型別來說明。

Module Module1
    Public Structure testStruct
        Public name As String
        Public number As Short
    End Structure

    Sub Main()

        Dim ts As testStruct
        Dim i As Integer
        Dim b As Boolean

        ' The following statement sets ts.name to Nothing and ts.number to 0.
        ts = Nothing

        ' The following statements set i to 0 and b to False.
        i = Nothing
        b = Nothing

        Console.WriteLine("ts.name: " & ts.name)
        Console.WriteLine("ts.number: " & ts.number)
        Console.WriteLine("i: " & i)
        Console.WriteLine("b: " & b)

    End Sub

End Module

如果變數為參考型別,Nothing 的值表示變數將不與任何的物件相關。 變數具有 null 值。 以下範例就是示範這項作業。

Module Module1

    Sub Main()

        Dim testObject As Object
        ' The following statement sets testObject so that it does not refer to
        ' any instance.
        testObject = Nothing

        Dim tc As New TestClass
        tc = Nothing
        ' The fields of tc cannot be accessed. The following statement causes 
        ' a NullReferenceException at run time. (Compare to the assignment of
        ' Nothing to structure ts in the previous example.)
        'Console.WriteLine(tc.field1)

    End Sub

    Class TestClass
        Public field1 As Integer
        ' . . .
    End Class
End Module

若要測試 Nothing 值的參考和可為 Null 的型別變數,請使用 Is 運算子或 IsNot 運算子。 使用等號的比較 (例如 someVar = Nothing) 一律會評估為 Nothing。 下列範例示範使用 Is 和 IsNot 運算子的比較。

Module Module1
    Sub Main()

        Dim testObject As Object
        testObject = Nothing
        ' The following statement displays "True".
        Console.WriteLine(testObject Is Nothing)

        Dim tc As New TestClass
        tc = Nothing
        ' The following statement displays "False".
        Console.WriteLine(tc IsNot Nothing)

        Dim n? As Integer
        ' The following statement displays "True".
        Console.WriteLine(n Is Nothing)
        n = 4
        ' The following statement displays "False".
        Console.WriteLine(n Is Nothing)
        n = Nothing
        ' The following statement displays "False".
        Console.WriteLine(n IsNot Nothing)

    End Sub

    Class TestClass
        Public field1 As Integer
        Dim field2 As Boolean
    End Class
End Module

如需詳細資訊與範例,請參閱可為 Null 的實值型別 (Visual Basic)

當您指派 Nothing 給物件變數時,此變數即不再參考至任一個物件執行個體。 如果此變數之前已參考至某執行個體,將它設定為 Nothing 並不會終止該執行個體本身。 只有在記憶體回收行程 (Garbage Collector,GC) 偵測到沒有餘留現用參考之後,執行個體才會終止,且與它相關的記憶體和系統資源會被釋放。

請參閱

參考

Dim 陳述式 (Visual Basic)

Is 運算子 (Visual Basic)

IsNot 運算子 (Visual Basic)

概念

物件存留期:物件的建立和終結 (Visual Basic)

Visual Basic 中的存留期

可為 Null 的實值型別 (Visual Basic)