访问另一个模块上的变量时出错?

时间:2016-10-05 18:15:58

标签: arrays vb.net global-variables

我有一个模块从数据网格中获取值,并将每行中的标记放入字符串数组中。我在另一个模块上调用该数组字符串,但我得到的对象没有设置为对象的实例。为什么?我想要完成的是将所有标记组合成一个字符串或集合数组,并能够在另一个模块上访问它。

'my main module
Public Class myMainModule
   Public Shared myArray() As String

   ......
   .......
   Public sub doSomething()
     Dim myArray As New List(Of String)
     For Each row As DataGridViewRow In mydatagrid.Rows
         If row.Cells("mycheckbox").Value = True Then
             myArray.Add(row.Tag)
         End If
     Next
  End Sub
End Class


'....then i'm calling it from another module:

Public Class myOtherModule
   Public sub doit()
     For Each value As String In myMainModule.myArray
         Debug.Print(value)
     Next
   End Sub
End Class

1 个答案:

答案 0 :(得分:1)

在尝试调用之前,需要初始化数组。目前是Nothing

Public Class MyMainModule
    Public Shared MyArray() As String

    Public Shared Sub DoSomething()
        Dim myList As New List(Of String)
        For Each row As DataGridViewRow In mydatagrid.Rows
         If row.Cells("mycheckbox").Value = True Then
             myList.Add(row.Tag)
         End If
        Next

        MyArray = myList.ToArray()
    End Sub
End Class

Public Class MyOtherModule
    Public Sub Foo()
        MyMainModule.DoSomething() 
        For Each value As String In MyMainModule.MyArray
            Debug.Print(value)
        Next
    End Sub
End Class

另一件事是你需要注意命名。我相信你很困惑,因为你有一个名为myArray的字段,但也有一个名为myArray的本地变量。您使用的是您创建的List(Of T)的局部变量,而不是数组。

相关问题