使用.GetValueOrDefault(0)和If(变量,0)与可空类型之间有什么区别吗?

时间:2010-03-09 00:51:25

标签: vb.net nullable boxing unboxing

下面两种方法之间用于计算c ...特别是装箱/拆箱问题有什么区别吗?

Dim a As Integer? = 10
Dim b As Integer? = Nothing
Dim c As Integer

' Method 1
c = If(a, 0) + If(b, 0)

' Method 2
c = a.GetValueOrDefault(0) + b.GetValueOrDefault(0)

3 个答案:

答案 0 :(得分:1)

根据Reflector,您的代码片段中的IL会反编译为:

Public Shared Sub Main()
    Dim a As Integer? = 10
    Dim b As Integer? = Nothing
    Dim c As Integer = (IIf(a.HasValue, a.GetValueOrDefault, 0) + IIf(b.HasValue, b.GetValueOrDefault, 0))
    c = (a.GetValueOrDefault(0) + b.GetValueOrDefault(0))
End Sub

[编辑]然后查看反射函数GetValueOrDefault()GetValueOrDefault(T defaultValue)分别给出以下内容:

Public Function GetValueOrDefault() As T
    Return Me.value
End Function

Public Function GetValueOrDefault(ByVal defaultValue As T) As T
    If Not Me.HasValue Then
        Return defaultValue
    End If
    Return Me.value
End Function

表明任何一种形式都有效地完全相同

答案 1 :(得分:1)

c = If(a,0)+ If(b,0)语句被编译为:

  Dim tmpa As Integer
  If a.HasValue Then
    tmpa = a.GetValueOrDefault()
  Else
    tmpa = 0
  End If
  Dim tmpb As Integer
  If b.HasValue Then
    tmpb = b.GetValueOrDefault()
  Else
    tmpb = 0
  End If
  c = tmpa + tmpb

第二个代码段完全按原样编译。这是明显的赢家。

答案 2 :(得分:0)

a.GetValueOrDefault(0)If(a, 0)

的稍微高效的版本

a.GetValueOrDefault()a.GetValueOrDefault(0)

的稍微高效的版本

当然,这仅适用于数字类型。