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

标签 c# .net vb.net nullable

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

VB:

  1. 如果 v 什么都不是
  2. If v.HasValue Then

C#:

  1. 如果(v == null)
  2. if (!v.HasValue)

最佳答案

没有区别 - 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() 的调用。

关于c# - 检查 nullable 是否有值的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926184/

相关文章:

VB.NET - 如何将大量事件添加到单个句柄?

c# - 字母数字和特殊字符的正则表达式

sqlbulkcopy,我想覆盖数据库中的当前行

c# - Windows 窗体设计器错误 "Illegal characters in path."

c# - 如何在 AX 查询服务中格式化 DateTime 比较值

c# - 在 TFS 构建服务器上运行单元测试 Fakes Framework |错误

c# - 我需要显式处理 SqlDataAdapter 吗?

.net - 如何模拟(使用最小起订量)Unity 方法

.net - 使用 LumenWorks 中的 CsvReader 和 ";"分隔符

c# - 手势到文本识别、OCR 或基于手势的 native .NET 库