VB.NET使用For Each循环遍历集合时如何处理Nothing空引用异常
解决方案
当然可以,你只需要在外层遍历到Person对象后、遍历其Names集合前,先加一层Names属性的非空校验即可,修正后的For Each写法如下:
Dim Counter As Integer = 0 Dim AllNames As String = String.Empty For Each individual As Person In PeopleContacts ' 先检查当前Person的Names集合是否为空,避免遍历空集合抛出空引用异常 If individual.Names IsNot Nothing Then For Each indName As Name In individual.Names If indName IsNot Nothing Then Counter += 1 AllNames &= Counter.ToString & ": " & indName.DisplayName & vbCrLf End If Next End If Next
逻辑说明
- 你之前的异常是因为尝试遍历
individual.Names这个空引用对象,而非内部的Name元素为空,原来的校验逻辑位置不对才没有生效 - 保留For Each结构的同时,只需要把非空校验提前到遍历Names集合之前,就能达到和下标遍历完全一致的效果,可读性和可维护性也更高
可选优化建议
如果Name集合的元素数量较多,直接拼接String会产生大量临时对象,性能较差,可以改用StringBuilder优化:
Dim Counter As Integer = 0 Dim AllNamesBuilder As New System.Text.StringBuilder() For Each individual As Person In PeopleContacts If individual.Names IsNot Nothing Then For Each indName As Name In individual.Names If indName IsNot Nothing Then Counter += 1 AllNamesBuilder.AppendLine($"{Counter}: {indName.DisplayName}") End If Next End If Next ' 最后统一转换为字符串 Dim AllNames As String = AllNamesBuilder.ToString()
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

