Is there any difference between myNullableLong.HasValue and myNullableLong != null?

前端 未结 3 475
清歌不尽
清歌不尽 2020-12-29 01:29

When I have a nullable long, for example, is there any difference between

myNullableLong.HasValue 

and

myNullableLong !=          


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 02:04

    It's just syntactic sugar. They will behave exactly the same way - the nullity test actually gets compiled into a call to HasValue anyway.

    Sample:

    public class Test
    {
        static void Main()
        {
            int? x = 0;
            bool y = x.HasValue;
            bool z = x != null;
        }
    }
    

    IL:

    .method private hidebysig static void  Main() cil managed
    {
      .entrypoint
      // Code size       25 (0x19)
      .maxstack  2
      .locals init (valuetype [mscorlib]System.Nullable`1 V_0)
      IL_0000:  ldloca.s   V_0
      IL_0002:  ldc.i4.0
      IL_0003:  call       instance void valuetype [mscorlib]System.Nullable`1::.ctor(!0)
      IL_0008:  ldloca.s   V_0
      IL_000a:  call       instance bool valuetype [mscorlib]System.Nullable`1::get_HasValue()
      IL_000f:  pop
      IL_0010:  ldloca.s   V_0
      IL_0012:  call       instance bool valuetype [mscorlib]System.Nullable`1::get_HasValue()
      IL_0017:  pop
      IL_0018:  ret
    } // end of method Test::Main
    

提交回复
热议问题