【发布时间】:2018-05-15 13:44:25
【问题描述】:
在我的程序中,我使用 WMI 接口来查询有关程序运行的硬件的大量信息。然后,我将获取该信息并将其放入列表中以帮助稍后显示它,但目前除此之外并没有做太多其他事情。到目前为止,这种方法效果很好,但有一个主要问题:有时查询是/返回(还不知道是哪一个!)Nothing 并导致NullReferenceException。
现在,显然我可以将它包装在 Try/Catch 中,然后继续我的快乐之路。但是,我想避免这样做,因为我将查询数百位信息,其中数百位可能会导致异常。这只是草率的编程,大大减慢了我的程序!
我的问题是:我要检查什么才能使用 If 而不是 Try?我将把我当前的代码放在下面,然后列出我已经尝试过的解决方案。
Public Shared Function GetSomeInfo() As List(Of String)
Dim ret As New List(Of String)
Dim sq As New Management.SelectQuery("Win32_Processor")
Dim mos As New Management.ManagementObjectSearcher(sq)
For Each info As Management.ManagementObject In mos.Get()
ret.Add(TryQuery(info, "Name"))
ret.Add(TryQuery(info, "Caption")) 'this query may result in Nothing somewhere...
Next
Return ret
End Function
Private Shared Function TryQuery(ByRef info As
Management.ManagementObject, ByVal strID As String) As String
Try
Return strID & ": " & info(strID).ToString 'exception obviously thrown here...but WHERE?
Catch ex As NullReferenceException
Return String.Empty
Catch ex As Management.ManagementException
Return String.Empty
End Try
End Function
所以,这就是我尝试使用这个Try 的方法:
If Not info Is Nothing Then ... 仍然导致一些未捕获的异常
If Not info(strID) Is Nothing Then ... 还是有异常
If Not info.Equals(Nothing) Then ...绝望
If Not Info(strID).ToString Is Nothing ...:(
我根本不知道在哪里 来检查 WMI 查询中抛出的这个异常。任何见解将不胜感激。谢谢!
【问题讨论】: