表示任何數據類型的預設值。 針對參考型別,預設值為 null 參考。 針對實值型別,預設值取決於實值型別是否可為 Null。
備註
針對不可為 Null 的實值類型, Nothing 在 Visual Basic 中與 null C# 不同。 在 Visual Basic 中,如果您將不可為 Null 實值類型的變數設定為 Nothing,則變數會設定為其宣告類型的預設值。 在 C# 中,如果您將不可為 Null 實值類型的變數指派給 null,就會發生編譯時期錯誤。
備註
Nothing 表示數據類型的預設值。 默認值取決於變數是實值型別還是參考型別。
實值型別的變數直接包含其值。 實值型別包括所有數值數據類型、 Boolean、 Char、、 Date所有結構和所有列舉。
參考類型的變數會將對象的參考儲存在記憶體中。 參考類型包括類別、陣列、委派和字串。 如需詳細資訊,請參閱 實值型別和參考型別。
如果變數是實值型別,則 的行為 Nothing 取決於變數是否為可為 Null 的數據類型。 若要表示可為 Null 的實值類型,請將修飾詞新增 ? 至類型名稱。
Nothing指定給可為 Null 的變數會將值設定為 null。 如需詳細資訊和範例,請參閱 可為 Null 的實值型別。
如果變數是不可為 Null 的實值型別,則 Nothing 指派給變數會將它設定為其宣告類型的預設值。 如果該類型包含變數成員,它們全都會設定為其預設值。 下列範例說明純量型別的這個。
Module Module1
Sub Main()
Dim ts As TestStruct
Dim i As Integer
Dim b As Boolean
' The following statement sets ts.Name to null 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}")
Console.ReadKey()
End Sub
Public Structure TestStruct
Public Name As String
Public Number As Integer
End Structure
End Module
如果變數是參考型別,指派 Nothing 給變數會將它設定為 null 變數類型的參考。 設定為參考的 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
若要檢查參考 (或可為 Null 的實值型別) 變數是否為 null,請一律使用 Is Nothing 或 IsNot Nothing。 不要使用 = Nothing 或 <> Nothing。
對於 Visual Basic 中的字串,空字串等於 Nothing。 因此, "" = Nothing 是真的。 這個事實讓您在使用字串時,選擇正確的比較特別重要。 雖然 myString = Nothing 並 myString <> Nothing 指出是否已設定非空白值,但我們強烈建議針對此目的使用 String.IsNullOrEmpty(myString) 。 使用 Is Nothing 和 IsNot Nothing 來判斷是否已設定任何值,包括空字串。
下列範例顯示使用和 IsNot 運算子的Is比較:
Module Module1
Sub Main()
Dim testObject As Object
testObject = Nothing
Console.WriteLine(testObject Is Nothing)
' Output: True
Dim tc As New TestClass
tc = Nothing
Console.WriteLine(tc IsNot Nothing)
' Output: False
' Declare a nullable value type.
Dim n? As Integer
Console.WriteLine(n Is Nothing)
' Output: True
n = 4
Console.WriteLine(n Is Nothing)
' Output: False
n = Nothing
Console.WriteLine(n IsNot Nothing)
' Output: False
Console.ReadKey()
End Sub
Class TestClass
Public Field1 As Integer
Private field2 As Boolean
End Class
End Module
如果您在不使用 子句的情況下 As 宣告變數,並將其設定為 Nothing,則變數的類型為 Object。 其中一個範例是 Dim something = Nothing。 當 已開啟且Option Infer關閉時Option Strict,就會發生編譯時期錯誤。
當您指派 Nothing 給物件變數時,它不再參考任何對象實例。 如果變數先前已參考實例,則將其設定為 Nothing 不會終止實例本身。 實例已終止,且與它相關聯的記憶體和系統資源只會在垃圾收集行程 (GC) 偵測到沒有作用中的參考剩餘之後釋放。
Nothing 與 DBNull 物件不同,代表未初始化的變體或不存在的資料庫數據行。