有什么区别?
(注意这只适用于VB.NET!在VBA中情况有所不同,详见下文。)
那么如何检查一个字符串是 null/Nothing 还是空的呢?
与其他答案所说的相反,您不需要使用String.IsNullOrEmpty 来检查Nothing 或空字符串,因为Visual Basic 中的= 运算符将Nothing 和空字符串视为等效。因此,在 VB.NET 中检查“null 或空字符串”的惯用方法是简单地使用 = "":
Dim s As String = Nothing
If s = "" Then Console.WriteLine("YES") ' Prints YES
因此,Not String.IsNullOrEmpty(s)、s <> ""、s <> String.Empty 和 s <> vbNullString 都是等价的。我更喜欢简洁的s <> "",但这主要是偏好和风格的问题。
这是否意味着我可以交替使用空字符串和 Nothing?
一般来说:没有。这种空字符串和 Nothing 的等价性仅适用于 VB.NET 的内置 = 和 <> 运算符以及 Microsoft.VisualBasic 命名空间中的大多数方法(Len(...)、Trim(...)、.. .)。一旦进入纯 .NET 领域(例如,通过使用基类库其余部分的方法),Nothing 和空字符串的处理方式将有所不同:
Dim sNothing As String = Nothing
Dim sEmpty As String = ""
Console.WriteLine(sEmpty = sNothing) ' True
Console.WriteLine(sEmpty.Equals(sNothing)) ' False
Console.WriteLine(String.Equals(sEmpty, sNothing)) ' False
Console.WriteLine(Len(sEmpty)) ' 0
Console.WriteLine(Len(sNothing)) ' 0
Console.WriteLine(sEmpty.Length) ' 0
Console.WriteLine(sNothing.Length) ' throws a NullReferenceException
为什么vbNullString 被定义为Nothing 而不是""?
向后兼容性。在 VBA(和“VB Classic”)中,vbNullString 可用于获取“空字符串引用”¹。在 VBA 中,vbNullString 被视为空字符串 "",但在与非 VB 代码交互时,vbNullString was mapped to the NULL pointer and "" was mapped to an empty string。
在 VB.NET 中使用 PInvoke 时,Nothing 映射到 NULL 指针,"" 映射到空字符串,因此在 VB 中让旧常量 vbNullString 等于 Nothing 是有意义的。网。
¹这与 VBA 的 Null 和 Empty 完全不同,它们是特殊的 Variant 子类型,而 VBA 的 Nothing 在 VBA 中仅适用于对象而不适用于字符串。