假设v是可空的,我想知道这些用法之间的含义/差异是什么:
VB:
>如果v则没有
>如果v.HasValue那么
C#:
> if(v == null)
> if(!v.HasValue)
解决方法:
没有区别 – 没有编译使用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()的调用.