我以前总是检查 null (VB.NET 中的 Nothing)
这种做法并不完全正确。 Nothing
不等同于 null
;当使用 =
操作符将其赋值或与可空类型(引用类型或 Nullable<T>
)进行比较时,Nothing
表示 null
;当使用 Is Nothing
进行比较时,也表示 null
。而当将其赋值或与非可空值类型进行比较时,Nothing
表示该类型的默认值。
因此在 VB 中:
Dim b as Boolean = 0 = Nothing ' b is True
“不是”和C#不一样:
bool b = 0 == null; // b is false
但更多的是:
bool b = 0 == default(int)
所以,在VB.NET中,default(T)
的等价物确实是Nothing
,当不使用Is
进行比较时。
在VB.NET中,如果val
不可空,则不允许使用val Is Nothing
,而在C#中,您可以使用val == null
,但会导致警告(且始终结果为false
)。
在VB.NET中,您可以对可能为空的泛型类型执行val Is Nothing
,C#也类似,使用val == null
进行检查,此时检查是val
是否为可空类型并且是否设置为空(通常情况下是无浪费的,对于非可空类型,JIT编译器知道val == null
/ val Is Nothing
永远不会发生,因此会优化掉任何可能发生的操作)。
以下VB.NET和C#方法是等效的:
public static bool Demonstrate<T>(T x)
{
T y = default(T);
bool isNull = x == null;
bool isDefault = x.Equals(default(T));
int zero = default(int)
return zero == default(int);
}
Public Shared Function Demonstrate(Of T)(x As T) As Boolean
Dim y As T = Nothing
Dim isNull As Boolean = x Is Nothing
Dim isDefault As Boolean = x.Equals(Nothing)
Dim zero As Integer = Nothing
Return zero = Nothing
End Function