myNullableLong.HasValue和myNullableLong!= null之间有什么区别吗?

时间:2011-03-08 14:34:33

标签: c# nullable

例如,当我有一个可以为空的长度时,

之间是否有任何区别
myNullableLong.HasValue 

myNullableLong != null

...还是只是'语法糖'?

3 个答案:

答案 0 :(得分:55)

这只是语法糖。它们的行为方式完全相同 - 无论如何,无效测试实际上都被编译成HasValue的调用。

样品:

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<int32> V_0)
  IL_0000:  ldloca.s   V_0
  IL_0002:  ldc.i4.0
  IL_0003:  call       instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)
  IL_0008:  ldloca.s   V_0
  IL_000a:  call       instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_000f:  pop
  IL_0010:  ldloca.s   V_0
  IL_0012:  call       instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_0017:  pop
  IL_0018:  ret
} // end of method Test::Main

答案 1 :(得分:8)

这是句法糖; Nullable<T>实际上是struct,因此实际不能null;编译器将与null(与您的第二个示例相比)的调用转换为对HasValue的调用。

请注意,将Nullable<T>装入object会导致T(如果有值)或null(如果是)不)。

int? foo = 10; // Nullable<int> with a value of 10 and HasValue = true
int? bar = null; // Nullable<int> with a value of 0 and HasValue = false

object fooObj = foo; // boxes the int 10
object barObj = bar; // boxes null

Console.WriteLine(fooObj.GetType()) // System.Int32
Console.WriteLine(barObj.GetType()) // NullReferenceException

答案 2 :(得分:3)

没有

C#编译器内置了对Nullable<T>的支持,并将涉及null的相等操作转换为对结构成员的调用。

n != nulln.HasValue都将编译为相同的IL。