【问题标题】:Storing variables generated by a while loop存储由 while 循环生成的变量
【发布时间】:2016-07-01 09:59:07
【问题描述】:

我有一个解析 csv 文件的 while 循环,并将变量插入到一系列数组中。这是由我的主窗体上的按钮调用的。

这些变量用于图表(在同一个子表中)和数据网格,它位于单独的表单中。

第一次单击该按钮时,一切正常,但是如果我第二次单击它,则不会填充单独表单上的数据网格,因为我丢失了变量。

所以在解析 CSV 文件的 while 循环中,我有这个:

frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)

我尝试将变量公开,但是因为它们是数组,并且是从 while 循环构造的,我似乎无法公开它们。

我的代码(为简洁而编辑)

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

   Dim sFile As String = strFileName
    ' get the minimum and maximum frequencies
    Dim Lines As Collections.Generic.IEnumerable(Of String) = File.ReadLines(strFileName)
    Dim Line0 As String = Lines.FirstOrDefault
    Dim LineN As String = Lines.LastOrDefault
    Dim lowestFreq As String() = Line0.Split(New Char() {","c})
    Dim highestFreq As String() = LineN.Split(New Char() {","c})
    Dim lowFreq As String = lowestFreq(0)
    Dim highFreq As String = highestFreq(0)
    Dim refFrequencyX = Lines(18)
    Dim refFreq As String() = refFrequencyX.Split(New Char() {","c})
    Dim ScaleFactor As String = refFreq(1)

    Using sr As New StreamReader(sFile)
        While Not sr.EndOfStream
            Dim sLine As String = sr.ReadLine()
            If Not String.IsNullOrWhiteSpace(sLine) Then
                sData = sLine.Split(","c)
                arrName.Add(sData(0).Trim())
                arrValue.Add(sData(1).Trim())
            End If

            Dim freq As Decimal = sData(0)
            Dim dBu As Decimal = sData(1)
            Dim voltage As Decimal = sData(1)
            ' dbnorm - normalise output to 0dBu ref 1kHz
            Dim dbnorm = Math.Round(dBu - ScaleFactor, 4)
            frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)
            Chart1.Series(0).Points.AddXY(freq, dbnorm)

        End While
    End Using

' ( chart is constructed here )

end sub

如何使这些数组变量成为全局变量?

请原谅我的伪劣代码 - 我这样做是一种爱好,并在我不断学习的过程中学习。

【问题讨论】:

标签: arrays vb.net csv variables datagrid


【解决方案1】:

我通过在模块中添加一个公共类来解决这个问题。

在“公共类”中,我有“公共共享子”用于我想从代码中的任何位置访问的子。

例子:

Public Module Module1

<various public variables here>

Public Class MyData

        Public Shared Sub debugTempFile()
            ' DEBUG
            Dim mytempFolder As String = Path.GetTempPath()
            Dim MyOutFile As String = mytempFolder + "outfile.txt"
            Dim myfile As System.IO.StreamWriter
            myfile = My.Computer.FileSystem.OpenTextFileWriter(MyOutFile, True)
            myfile.WriteLine(debugdata)
            myfile.Close()
            ' END DEBUG
        End Sub
End Class
End Module

可以使用 call 语句从任何地方调用此 Public Sub:

Call MyData.debugTempFile()

我希望这对像我这样的其他初学者有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2011-03-07
    • 2022-07-21
    • 1970-01-01
    • 2013-10-29
    • 2018-03-05
    相关资源
    最近更新 更多