下面两种计算 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)
最佳答案
根据 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
指示任何一种形式都有效地完成相同的事情
关于vb.net - 将 .GetValueOrDefault(0) 和 If(variable, 0) 与可空类型一起使用有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2405923/