【问题标题】:What is the difference between vbNullString, String.Empty and ""?vbNullString、String.Empty 和“”有什么区别?
【发布时间】:2014-06-01 13:24:00
【问题描述】:

所有这些

  • txtUsername.Text <> vbNullString
  • txtUsername.Text <> String.Empty
  • txtUsername.Text <> ""

似乎返回相同的结果。那么vbNullStringString.Empty""有什么区别呢?

【问题讨论】:

  • IsNullOrEmpty()怎么样
  • Arman 的意思是String.IsNullOrEmpty()

标签: vb.net string-comparison


【解决方案1】:

有什么区别?

  • String.Empty"" 都表示长度为零的字符串。

  • the documentation相反,它声称vbNullString[r]表示一个零长度字符串”,vbNullString实际上是Nothingnull in C#,见Reference Source)。

(注意这只适用于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.Emptys <> 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 的 NullEmpty 完全不同,它们是特殊的 Variant 子类型,而 VBA 的 Nothing 在 VBA 中仅适用于对象而不适用于字符串。

【讨论】:

  • 我没有发现vbNullString 等于Nothing。感谢那!该文档非常矛盾,因为它实际上还表明这是一个定义为Nothing 的常量:public const string vbNullString = null;
【解决方案2】:

如果要将值插入 MS-SQL 数据库并且如果列不允许 null(Not null),则 strValue=vbNullString 将生成异常,但 strValue="" 将插入空格。

【讨论】:

  • 这只不过是一个非常具体的案例,说明了vbNullString = Nothing这一事实的后果,正如this answer已经涵盖的那样......
【解决方案3】:

vbNullString 是一个常量,VB6 出来的可能性更大,String.Empty"" 是一样的,有人说有性能差异,但事实并非如此,用什么是你的选择。

要检查字符串是否为空,您可以使用If String.IsNullOrEmpty(String)。优点是它还会检查 null,因为 string 是一个类,因此是一个引用类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2011-05-11
    • 2011-09-07
    • 2010-10-02
    • 2011-12-12
    • 2010-09-16
    • 2012-03-14
    相关资源
    最近更新 更多