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 不会终止该实例本身。 只有在垃圾回收器 (GC) 检测到没有任何剩余的活动的引用时,才会终止该实例,并释放与其关联的内存和系统资源。

请参见

参考

Dim 语句 (Visual Basic)

Is 运算符 (Visual Basic)

IsNot 运算符 (Visual Basic)

概念

对象生存期:如何创建和销毁对象 (Visual Basic)

Visual Basic 中的生存期

可以为 Null 的值类型 (Visual Basic)