区分空值和空值的最有效方法是什么?我要:
CStr("")
评估为True
,而CStr(Nothing)
评估为False
答案 0 :(得分:2)
HasValue
属性适用于可为空的值类型。对于引用类型(String
是引用类型,所有类也是如此),您只需将其与Nothing
进行比较:
If myString Is Nothing Then
请注意使用Is
运算符。那是为了引用相等,而=
运算符是为了值相等。大多数类型仅支持一种或另一种,但是String
是同时支持这两种类型的少数类型之一,因为它们都很有意义。尝试一下以查看它们各自的行为:
Dim nullString As String = Nothing
Dim emptyString As String = String.Empty
If nullString Is Nothing Then
Console.WriteLine("nullString Is Nothing")
End If
If nullString = Nothing Then
Console.WriteLine("nullString = Nothing")
End If
If nullString Is String.Empty Then
Console.WriteLine("nullString Is String.Empty")
End If
If nullString = String.Empty Then
Console.WriteLine("nullString = String.Empty")
End If
If emptyString Is Nothing Then
Console.WriteLine("emptyString Is Nothing")
End If
If emptyString = Nothing Then
Console.WriteLine("emptyString = Nothing")
End If
If emptyString Is String.Empty Then
Console.WriteLine("emptyString Is String.Empty")
End If
If emptyString = String.Empty Then
Console.WriteLine("emptyString = String.Empty")
End If
引用相等性检查两个引用是否引用同一个对象,而值相等性检查两个值是否相等,无论它们是什么对象。 Nothing
和String.Empty
在引用相等的上下文中是不同的,因为一个是对象,一个不是对象,但是在值相等的上下文中它们被认为是等效的。
答案 1 :(得分:-2)
这里是:
<Runtime.CompilerServices.Extension>
Public Function HasValue(s As String)
Return TypeOf (s) Is String
End Function
等效性更好:(来自jmcilhinney的回答)
<Runtime.CompilerServices.Extension>
Public Function HasValue(s As String)
Return s IsNot Nothing
End Function
也是10000种不同长度的字符串上各种方法的基准:
函数(x作为字符串) .............. :: 总时间(相对效率 %)
TypeName(x)=“ String” .....................:0.850ms(17.1%)
VarType(x)= VariantType.String ........:0.590ms(24.6%)
TypeOf(x)是字符串...........................:0.150ms(96.7%)
x不是什么..................:0.145ms(100%)