.net里 dbnull , nothing 关系...请看代码

来源:百度知道 编辑:UC知道 时间:2024/05/24 23:32:07
Dim s As String = Nothing
Dim b As System.DBNull

If IsDBNull(b) = True Then
MsgBox("null1")
End If

If s Is b Then
MsgBox("null2")
End If

测试下来,只报null2 ,而null1 却不报
这是为何?
IS 是比较两个引用类型,但为何却相等呢?
谢谢 我试了
sIsDBNull

Public Shared Function sIsDBNull(ByVal Expression As Object) As Boolean

Return TypeOf Expression Is DBNull
End Function
再试
Dim x AsString = Nothing
If sIsDBNull(x)
依然是false
那 'If (Expression Is Nothing) Then
' Return False
'End If有何意义
有其他工具推荐吗

以下是用 Reflector 反编译以后得到的代码:

Dim b As DBNull ' 注意以下这里:b 没有初始化,目前值为 Nothing
Dim s As String = Nothing
If Information.IsDBNull(b) Then
Interaction.MsgBox("null1", MsgBoxStyle.OkOnly, Nothing)
End If
If (s Is b) Then
Interaction.MsgBox("null2", MsgBoxStyle.OkOnly, Nothing)
End If

首先回答第二个 null2 的问题:既然两个目前都是 Nothing,s Is b 当然相等。实际上反编译成 C# 可以知道,a Is b 相当于 a == b。

第一个 null1 的问题:IsDBNull 的反编译是这样的:

Public Shared Function IsDBNull(ByVal Expression As Object) As Boolean
If (Expression Is Nothing) Then
Return False
End If
Return TypeOf Expression Is DBNull
End Function

因为 b 是 Nothing,所以是 False。

Reflector 是个很好的利器,博主一定要下载一个。HoHo~

===============================

补充:

现在看 Reflector 的 Visual Basic 反编码已经没有意义了。不妨看看它的 IL 反汇编:

.method public static bool