String null vs“”

时间:2014-10-22 16:44:02

标签: c# vb.net null

好的,我正在将某人的代码从VB.Net转换为C#。我想知道字符串是否设置为"",是否与设置为null相同?例如,将使用以下代码:

string word = "";
bool boolValue = false;

if(string == null)
{
  boolValue = true;
}

这样最终会将boolValue设置为true,或者将字设置为""或者两个不同的东西?我的直觉告诉我,这是不同的。那""只是让它成为一个空字符串。

3 个答案:

答案 0 :(得分:9)

不,他们绝对不是一回事。 ""是一个空字符串。 null没有任何价值。

.NET有许多实用程序方法可以帮助您检查不同的情况。您可以查看string.IsNullOrEmptystring.IsNullOrWhitespace

答案 1 :(得分:2)

不,它不是同一个字符串。如果字符串为null,则不分配对象。这意味着您无法访问此字符串 - 您将获得异常。但是,如果字符串是"",则它现在被分配对象并且您可以访问该对象(您可以获得该字符串的长度,在这种情况下将为0)。

答案 2 :(得分:-1)

您的混淆可能源于VB在应用于字符串时模糊/不一致的“Nothing”概念,具体取决于是否使用了'='或'Is'运算符,如这些示例所示:

Dim s1 As String = ""
If s1 = Nothing Then MsgBox("= Nothing") 'true
If s1 Is Nothing Then MsgBox("Is Nothing") 'false

Dim s2 As String = Nothing
If s2 = Nothing Then MsgBox("= Nothing") 'true - both 'Nothing' and "" pass the "= Nothing" test!
If s2 Is Nothing Then MsgBox("Is Nothing") 'true

C#字符串没有歧义。