问题描述
为什么第一个 if 语句的计算结果为 true?我知道如果我使用is"而不是=",那么它不会评估为真.如果我用Foo"替换 String.Empty,它不会评估为真.String.Empty 和 "Foo" 都具有相同类型的 String,那么为什么一个计算结果为 true 而另一个不计算?
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?
//this evaluates to true
If Nothing = String.Empty Then
End If
//this evaluates to false
If Nothing = "Foo" Then
End If
推荐答案
VB.net 中没有任何东西是类型的默认值.语言规范在第 2.4.7 节中说:
Nothing in VB.net is the default value for a type. The language spec says in section 2.4.7:
Nothing 是一个特殊的文字;它没有类型并且可以转换为类型系统中的所有类型,包括类型参数.当转换为特定类型时,它相当于该类型的默认值.
因此,当您针对 String.Empty 进行测试时,Nothing 会转换为长度为 0 的字符串. Is 运算符应该用于针对 Nothing 进行测试,并且 String.Empty.Equals(Nothing) 也会返回 false.
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.
这篇关于Nothing = String.Empty(为什么这些相等?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!