Nothing = String.Empty(为什么这些相等?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2633166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nothing = String.Empty (Why are these equal?)
提问by Justin Helgerson
Why does the first if statement evaluate to true? I know if I use "is" instead of "=" then it won't evaluate to true. If I replace String.Empty with "Foo" it doesn't evaluate to true. Both String.Empty and "Foo" have the same type of String, so why does one evaluate to true and the other doesn't?
为什么第一个 if 语句评估为真?我知道如果我使用“is”而不是“=”,那么它不会评估为真。如果我用“Foo”替换 String.Empty,它不会评估为真。String.Empty 和 "Foo" 都具有相同类型的 String,那么为什么一个计算结果为 true 而另一个不计算呢?
//this evaluates to true
If Nothing = String.Empty Then
End If
//this evaluates to false
If Nothing = "Foo" Then
End If
采纳答案by Rebecca Chernoff
Nothing in VB.net is the default value for a type. The language specsays in section 2.4.7:
VB.net 中没有任何内容是类型的默认值。该语言规范说,在节2.4.7:
Nothing is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.
没有什么是特殊的文字;它没有类型并且可以转换为类型系统中的所有类型,包括类型参数。当转换为特定类型时,它相当于该类型的默认值。
So, when you test against String.Empty, Nothing is converted to a string, which has a length 0. The Is operator should be used for testing against Nothing, and String.Empty.Equals(Nothing) will also return false.
因此,当您针对 String.Empty 进行测试时,Nothing 将转换为长度为 0 的字符串。应该使用 Is 运算符来针对 Nothing 进行测试,并且 String.Empty.Equals(Nothing) 也将返回 false。
回答by Heinzi
It's a special case of VB's =
and <>
operators.
这是 VB=
和<>
运算符的特例。
The Language Specificationstates in Section 11.14:
在语言规范中第11.14节规定:
When doing a string comparison, a null reference is equivalent to the string literal "".
进行字符串比较时,空引用等效于字符串文字“”。
If you are interested in further details, I have written an in-depth comparison of vbNullString
, String.Empty
, ""
and Nothing
in VB.NET here:
如果您有兴趣进一步的细节,我写的深入比较vbNullString
,String.Empty
,""
和Nothing
在VB.NET这里:
回答by Amber
回答by DanielRuzo
Related to this topic, if you use a string variable initialized with "nothing" to be assigned to the property "value" of a SqlParameter that parameter is ignored, not included in the command sent to the server, and a missing parameter error is thrown. If you initialize that variable with string.empty everything goes fine.
与本主题相关,如果您使用初始化为“nothing”的字符串变量分配给 SqlParameter 的属性“value”,则该参数将被忽略,未包含在发送到服务器的命令中,并且会引发丢失参数错误. 如果您使用 string.empty 初始化该变量,则一切正常。
//This doesn't work
Dim myString as String = nothing
mySqlCommand.Parameters.Add("@MyParameter", SqlDbType.Char).Value = myString
//This works
Dim myString as String = string.empty
mySqlCommand.Parameters.Add("@MyParameter", SqlDbType.Char).Value = myString