在VB中使用此代码时,出现错误:
System.InvalidCastException:'无法将类型为'System.Collections.ArrayList'的对象转换为类型为'System.Collections.Generic.IEnumerable`1 [System.String]'。'
有人可以给我正确的用法吗?
完整代码:
Public Class Form1
Dim OutputArray As New ArrayList
Dim i = 0
Dim Registrationdata
Dim FileName As String = Application.StartupPath & "\Output.txt"
Private Sub IssueTicket_Click(sender As Object, e As EventArgs) Handles IssueTicket.Click
Dim Speed As Integer
If Integer.TryParse(Speedbox.Text(), Speed) Then
If Speed <= 20 Or Speed > 300 Then
MessageBox.Show("Please enter a valid speed between 20-200")
ElseIf Registrationbox.Text() = Nothing Or Not Registrationbox.Text() Like "???? ???" Then
MessageBox.Show("Please enter a vaild registration to continue e.g '1234 123'.")
ElseIf Not IDBox.Text().StartsWith("9") Or Not IDBox.TextLength = 6 Or Not IsNumeric(IDBox.Text()) Then
MessageBox.Show("Please enter a valid OfficerID starting with '9' and is 6 numbers long.")
Else
OutputArray.Add(Speed)
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
MessageBox.Show("Ticket saved")
i += 1
End If
End If
End Sub
Private Sub SaveToFile_Click(sender As Object, e As EventArgs) Handles SaveToFile.Click
Registrationbox.Text() = Registrationdata
IO.File.WriteAllLines(FileName, OutputArray)
End Sub
End Class
答案 0 :(得分:2)
要快速解决问题,您可以将代码更改为:
Dim OutputArray As New List(Of String)
...
OutputArray.Add(Speed.ToString())
OutputArray.Add(Registrationbox.Text())
OutputArray.Add(IDBox.Text())
您的代码存在的问题是ArrayList
没有实现IEnumerable接口,而List
却实现了IEnumerable接口,因此File.WriteAllText
可以工作;但是List(Of String)
希望所有项目均为字符串类型,因此您必须先将int转换为字符串,然后再将其推入列表。