如何检查列表对象是否为空?

How can I check if a list object is null?

如何检查项目对象是否为空?我有一个 returns 联系人列表,我想检查我的列表对象是否为 null 以防止 null 异常?

Dim list As New List(Of ContactU)
list = resource.ContactUs.ToList()
If list.Count <> 0 Then
    For Each item In list
        If item Then
            'Do the loop 
        End If
    Next
End If

您的问题标题与您的书面问题“如何检查项目是否为空?”相冲突。要回答这个问题,您需要检查变量 Is Nothing:

Dim list As List(Of ContactU) = resource.ContactUs.ToList()

If list Is Nothing Then
    ' Handle what happens when the list is Null/Nothing.
Else
    ' Handle what happens when the list is not Null/Nothing.
End If

判断变量是否为Null/Nothing时,关键字如下(IsNot为一个关键字):

If list IsNot Nothing Then

如果要检查变量是否为 IsNot Nothing 并在同一语句中检查变量的 属性,则必须使用 And 的 short-circuiting 版本或 Or:

If list IsNot Nothing AndAlso list.Count > 0 Then

这样,如果 list 为 Nothing,则 list.Count 不会被求值,也不会抛出空引用异常。