如何解决 VB 'If` 语句的 'End of statement expected' 编译器错误?

How do I solve an 'End of statement expected' compiler error for a VB 'If` statement?

我不太擅长 VB.net,主要使用 C#,我有以下 foreach 循环:

Dim pSources() As Integer = {}
pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId)

Try

    For Each intSelect As Integer In pSources 

        For Each li As ListItem In chkSources.Items 

            If Convert.ToInt32(li.Value) Equals(intSelect)
                li.Selected = True
            End If

        Next

    Next

Catch ex As Exception

End Try

我想检查 IntegerpSources 数组中的每个项目,以在复选框列表中找到适当的值,如果值匹配则检查复选框。

使用我目前的代码,我在进行 if 比较的那一行出现错误,这是错误:

End of statement expected

我该如何解决这个问题?

或者更好的是,我如何使用 LINQ 语句来检查值,然后在值包含在 pSources 数组中时检查复选框?

您的 IF 语句末尾需要一个 "THEN"。有一些不错的 C# 到 VB.NET 在线转换应用程序(例如这个 code converter from Telerik)——您可以尝试其中的一些来帮助您熟悉 VB.NET。

我看到的两个问题:

1) 正如 Russ 指出的那样,您需要在 If 之后添加一个 Then 语句。在VB中,语法是

If <boolean statement> Then
    <Some Code>
End If

2) 我在您的布尔语句中没有看到 . 加入 Equals。这只是无效的语法。就像评论中建议的那样,您可以在此处使用 = 运算符以更加清晰。如果您仍想使用 Equals,则在 Converter.ToInt32(li.Value)Equals 之间添加一个 .。您的最终代码应如下所示:

Dim pSources() As Integer = {}
pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId)

Try

    For Each intSelect As Integer In pSources 

        For Each li As ListItem In chkSources.Items 

            If Convert.ToInt32(li.Value).Equals(intSelect) Then
                li.Selected = True
            End If

        Next

    Next

Catch ex As Exception

End Try

这是我自己会做的...

下面的代码检查以确保 pSources 是某物并且其中也包含某物。 Integer.TryParse 如果无法解析则不会抛出异常,并且会在尝试进行比较之前短路...

 Dim pSources As New List(Of Integer)
 Dim intNumber As Integer = 0
 pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId)

 Try
    If pSources IsNot Nothing AndAlso pSources.Count > 0 Then
      For Each intSelect In pSources 
       For Each li As ListItem In chkSources.Items 
        If Integer.TryParse(li.Value.ToString, intNumber) AndAlso (intNumber = intSelect) Then
            li.Selected = True
        End If
       Next
      Next 
    End If

 Catch ex As Exception
  'Handle your exception...
 End Try

这个:

    Dim pSources = SCCC.GetSources(SysCompany, SysUser, ccHeaderId)

    Dim val = 0
    For l = 0 To chkSources.Items.Count - 1
        chkSources.SetSelected(l, Integer.TryParse(chkSources.Items(l).ToString, val) AndAlso pSources.Contains(val))
    Next