假设 v 是可空类型,我想知道以下使用方式的意义和区别:
VB:
VB:
- If v Is Nothing Then
- If v.HasValue Then
- if (v == null)
- if (!v.HasValue)
没有区别 - Is Nothing
编译后使用 HasValue
。例如,这个程序:
Public Class Test
Public Shared Sub Main()
Dim x As Nullable(Of Integer) = Nothing
Console.WriteLine(x Is Nothing)
End Sub
End Class
翻译成这种IL:
.method public static void Main() cil managed
{
.entrypoint
.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 )
// Code size 24 (0x18)
.maxstack 2
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0008: ldloca.s V_0
IL_000a: call instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_000f: ldc.i4.0
IL_0010: ceq
IL_0012: call void [mscorlib]System.Console::WriteLine(bool)
IL_0017: ret
} // end of method Test::Main
get_HasValue()
。完全没有区别。这只是您的风格偏好。
这两行代码将生成完全相同的IL代码:
if (!v.HasValue)
if (v == null)
您可以在 IL 中看到,在这两种情况下都调用了 Nullable::get_HasValue()。
抱歉,我用的是 C# 而不是 VB 来进行示例。
HasValue
属性。If v.HasValue Then
...
End