Sup*_*tar 65 vb.net null runtime-error
我想做的就是检查一个对象是否为空,但无论我做什么,如果它编译,它会抛出一个NullReferenceException只是试图检查!这就是我所做的:
If ((Not (comp.Container Is Nothing)) And (Not (comp.Container.Components Is Nothing))) Then
For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
fixUIIn(comp.Container.Components.Item(i), style)
Next
End If
If ((Not IsDBNull(comp.Container)) And (Not IsDBNull(comp.Container.Components))) Then
For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
fixUIIn(comp.Container.Components.Item(i), style)
Next
End If
If ((Not IsNothing(comp.Container)) And (Not IsNothing(comp.Container.Components))) Then
For i As Integer = 0 To comp.Container.Components.Count() - 1 Step 1
fixUIIn(comp.Container.Components.Item(i), style)
Next
End If
If ((Not (comp.Container Is DBNull.Value)) And (Not (comp.Container.Components Is DBNull.Value))) Then
For i As Integer = 0 To comp.Container.Components.Count() Step 1
fixUIIn(comp.Container.Components.Item(i), style)
Next
End If
Run Code Online (Sandbox Code Playgroud)
我查看了VB书籍,搜索了几个论坛,而且应该工作的一切都没有!很抱歉提出这样一个补救问题,但我只需要知道.
您知道,调试器说null对象是 comp.Container
Kon*_*lph 32
你的代码比必要的更混乱.
更换(Not (X Is Nothing))与X IsNot Nothing和省略外括号:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For i As Integer = 0 To comp.Container.Components.Count() - 1
fixUIIn(comp.Container.Components(i), style)
Next
End If
Run Code Online (Sandbox Code Playgroud)
更具可读性....还要注意我已经删除了冗余Step 1并且可能是多余的.Item.
但是(正如评论中所指出的那样),基于索引的循环无论如何都已经不再流行了.除非你绝对必须,否则不要使用它们.For Each改为使用:
If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
For Each component In comp.Container.Components
fixUIIn(component, style)
Next
End If
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
227599 次 |
| 最近记录: |