检查可空对象是否有值的正确方法

4
假设 v 是可空类型,我想知道以下使用方式的意义和区别:
VB:
  1. If v Is Nothing Then
  2. If v.HasValue Then
C#:
  1. if (v == null)
  2. if (!v.HasValue)

@BoltClock,你链接的问题是一个C#问题。从代码来看,这个问题是关于VB.NET的。这两种语言在可空类型方面确实有不同的细节,所以我不会把它称为重复问题。 - Joe White
1
@Joe White:从未知道-感谢您指出这一点。应该删除我的自动链接评论... - BoltClock
4个回答

4

没有区别 - 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()

3

1

完全没有区别。这只是您的风格偏好。

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

if (!v.HasValue)

if (v == null)

您可以在 IL 中看到,在这两种情况下都调用了 Nullable::get_HasValue()。

抱歉,我用的是 C# 而不是 VB 来进行示例。


-1
使用 HasValue 属性。
If v.HasValue Then
    ...
End

2
你能证明你的答案吗? - empi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接