0

希望人们能提供帮助!

我正在尝试创建一个组合框,其中填充了来自使用 , 作为断点分隔的文本文件中的信息。IE

objecta,grad,N,words,5,moretext

我需要 , 之间的各个区域作为整数/布尔值/字符串 .. 但我在让代码正常工作时遇到问题

我在网上搜索过,找到了这段代码,但它对我来说不能正常工作。也许我很愚蠢,但希望有人可以帮助我。帮助我哦,互联网大师!

Public Sub meritlist()
    Dim looksups As New ArrayList
    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    Dim rdr As IO.StreamReader = IO.File.OpenText(c:merits.txt")
    While Not rdr.EndOfStream
        Dim line As String = rdr.ReadLine()

        'Split the line by a comma:
        Dim arrayList = line.Split(",")

        'Get the right values: break down is as: Merit Name,Type,Shared,Carthan,Max,Pre-Req
        Dim meritname As Integer = arrayList(0)
        Dim merittype As String = arrayList(1)
        Dim meritshared As Boolean = arrayList(2)
        Dim carthan As String = arrayList(3)
        Dim meritmax As Integer = arrayList(4)
        Dim prereq As String = arrayList(5)

        cmoMRDro.Items.Add(New lookups(arrayList(0), arrayList(1)))

    End While
    rdr.Close()
End Sub
4

1 回答 1

1

我建议有 4 件事。

  1. 使用TextFieldParser类读取分隔/固定宽度的文本文件。他们更专业地从事这项工作,并且已经拥有正确处理它的代码。

  2. InitializeComponent不需要调用 to 。

  3. 创建一个结构/类来存储您的订单项,而不是原始变量。这样,您就可以更有条理地拥有它。

  4. 使用List该结构/类,而不是ArrayList

虽然您已经在做的事情可以通过一些修改来纠正,但我会这样做,保留我上面给出的所有建议。因此,您可以看到在此之后它变得多么容易:

Structure MeritListType
    Dim meritname As Integer
    Dim merittype As String
    Dim meritshared As Boolean
    Dim carthan As String
    Dim meritmax As Integer
    Dim prereq As String

    Public Sub New(ByVal data() As String)
        meritname = Integer.Parse(data(0))
        merittype = data(1)
        meritshared = Boolean.Parse(data(2))
        carthan = data(3)
        meritmax = Integer.Parse(data(4))
        prereq = data(5)
    End Sub
End Structure

Public Sub MeritList()
    Dim FileData As New List(Of MeritListType)
    Dim tfp As New FileIO.TextFieldParser("c:\merits.txt")
    tfp.TextFieldType = FileIO.FieldType.Delimited
    tfp.SetDelimiters(",")
    While Not tfp.EndOfData
        FileData.Add(New MeritListType(tfp.ReadFields))
    End While
    tfp.Close()

    '' you have the records in FileData
    '' do whaever you want to do with it here now

End Sub
于 2012-07-12T10:10:13.753 回答