首页 > 解决方案 > System.Array.FindAll () 的问题

问题描述

6年前做过vb。试图将大脑升级到 VB.NET

Private Sub BtnFindAll_Click(sender As Object, e As EventArgs) Handles BtnFindAll.Click

    Dim AutosArray() As String = {"Chrysler", "Corvette", "Lincoln", "Buick", "Ford", "Fiat", "Chevrolet", "Mercury"}
    Dim BooBee() As String

    ' The below line gets the error...
    BooBee = System.Array.FindAll(AutosArray, AddressOf MatchFunction)

    ' The below line gets the same error...
    'Dim BooBee() As String = Array.FindAll(AutosArray, AddressOf MatchFunction)

End Sub

Private Function MatchFunction(ByVal strAuto As String) As String
    If strAuto.IndexOf("c") > 1 Then
        Return strAuto
    End If
End Function

当我单击 BtnFindAll 时,我收到以下错误消息:

异常未处理 System.InvalidCastException:“从字符串“”到类型“布尔”的转换无效。

内部异常 FormatException:输入字符串的格式不正确。

标签: arraysvb.net

解决方案


MatchFunction 应该返回一个布尔值以与 FindAll 方法兼容

像这样的东西

Private Function MatchFunction(ByVal strAuto As String) As Boolean
    If strAuto.IndexOf("c") > 1 Then
        Return True
    Else
        Return False
    End If
End Function

您可以在 FindAll 文档的备注部分阅读这一点

还要考虑一下,现在有另一个选项可以使用 Linq 用一行来提取该信息

BooBee = AutosArray.Where(Function(x) x.IndexOf("c") > 1).ToArray()

推荐阅读