vb.net - 将 .GetValueOrDefault(0) 和 If(variable, 0) 与可空类型一起使用有什么区别吗?

标签 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)

最佳答案

根据 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/

相关文章:

kotlin - 我在 kotlin 安全调用中遇到重载解析歧义错误

kotlin - Kotlin可空JNI类型

scala - SparkSQL.createDataFrame 中出现奇怪的类型转换错误

python - 为什么 Python 的数组很慢?

vb.net - 在 VB.NET 中写入和读取 .ini 文件

mysql - 使用 dotnet String.Format 将数据保存到数据库失败

regex - 可空性(正则表达式)

java - 如何从 List<Integer> 中获取 IntStream?

javascript - 从嵌入式播放器捕获 SendPlayStateChangeEvents

mysql - 如何在 firebird 中插入另一个表中的行?