在Private Sub之间共享(String)列表

时间:2014-05-01 13:56:08

标签: vb.net sharing

在我的代码中,我基本上读了一个文本框并将每一行放入一个列表中(Of String) Dim" testblock"在下面的代码中

从那里我创建另一个列表(字符串)并在找到空格时拆分每一行。 Dim" block"在下面的代码中

现在我希望能够从项目的任何位置访问该列表。

如何在私有Sub(例如表单按钮)之间共享(String)列表?

Private Sub PhaseCodeBTN_Click(sender As Object, e As EventArgs) Handles PhaseCodeBTN.Click
    Dim testblock As New List(Of String)
    Dim lines As String() = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    Dim block As New List(Of String)

    For Each l As String In lines
        testblock.Add(l)
        Dim words As String() = BlockCodeBox.Text.Split(" ")
        For Each splitword As String In words
            block.Add(splitword)
        Next
    Next
    BlockCodeBox.Text = testblock(BlockNumBox.Text)
    WordCmdBox.Text = block(WordNumBox.Text)

End Sub

Private Sub PhaseBlackBTN_Click(sender As Object, e As EventArgs) Handles PhaseBlackBTN.Click

    WordCmdBox.Text = block(WordNumBox.Text)
End Sub

1 个答案:

答案 0 :(得分:0)

使用Public Shared Class创建List(Of String),以便在项目的任何位置使用它:

Public Shared Class DataHolder

    Private _block As New List(Of String)

    Public Property Block As List(Of String)
    Get
        Return _block
    End Get        
    Set
        _block = value
    End Set
    End Property

End Class

示例:

只需使用DataHolder.Block.Add(splitword)或以下步骤:

  1. 声明一个类变量block以在整个类中使用它:

    Private block As List(Of String)
    
  2. 在一些合适的函数/事件处理程序中初始化它,如Form_Load

    block = DataHolder.Block 
    
  3. 执行操作:

    block.Add(splitword)