C# 检查nullable是否有值的正确方法

C# 检查nullable是否有值的正确方法,c#,.net,vb.net,nullable,C#,.net,Vb.net,Nullable,假设v是可空的,我想知道这些用法之间的含义/区别是什么: VB: 如果v为零,则 如果v.HasValue那么 C#: 如果(v==null) 如果(!v.HasValue) 使用HasValue属性 If v.HasValue Then ... End 没有区别。你总是得到同样的结果。 不久前,我编写了一些单元测试来检查可空类型的不同行为:.没有区别-什么都没有编译为使用HasValue。例如,此程序: Public Class Test Public Shared Sub

假设v是可空的,我想知道这些用法之间的含义/区别是什么:

VB:

  • 如果v为零,则
  • 如果v.HasValue那么
  • C#:

  • 如果(v==null)
  • 如果(!v.HasValue)

  • 使用
    HasValue
    属性

    If v.HasValue Then
        ...
    End
    

    没有区别。你总是得到同样的结果。
    不久前,我编写了一些单元测试来检查可空类型的不同行为:.

    没有区别-
    什么都没有
    编译为使用
    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
    
    .method public static void Main()cil managed
    {
    .入口点
    .custom实例void[mscorlib]System.STAThreadAttribute::.ctor()=(01 00)
    //代码大小24(0x18)
    .maxstack 2
    .locals init(valuetype[mscorlib]System.Nullable`1 V_0)
    IL_0000:ldloca.s V_0
    IL_0002:initobj valuetype[mscorlib]系统。可为null`1
    IL_0008:ldloca.s V_0
    IL_000a:调用实例bool valuetype[mscorlib]System.Nullable`1::get_HasValue()
    IL_000f:ldc.i4.0
    IL_0010:ceq
    IL_0012:调用void[mscorlib]System.Console::WriteLine(bool)
    IL_0017:ret
    }//方法测试结束::Main
    

    注意对
    get\u HasValue()
    的调用绝对没有区别。这只是你的风格偏好

    这两行代码将生成完全相同的IL代码:

    if (!v.HasValue)
    
    if (v == null)
    
    您可以在IL中看到,在这两种情况下都调用了null::get_HasValue()


    抱歉,我是用C#而不是VB编写的示例。

    @BoltClock,您链接到的问题是C#问题。从代码来看,这个问题是关于VB.NET的。这两种语言在可空类型上确实有不同的折痕,所以我不认为这是重复的。@Joe White:不知道-谢谢你指出这一点。我的自动链接评论…你能证明你的答案吗?