全局结构数组给出NullReferenceException

时间:2014-12-27 06:55:12

标签: .net vb.net nullreferenceexception

这是结构的定义

Structure Ct

    Public name As String

    Structure Pt
        Public identity As String
    End Structure

    Public Pty() As Pt

End Structure


Public Cty() As Main.Ct

这是在名为main的模块中声明的。

然后运行位于另一个类的子例程中的这段代码

Dim i As Integer = 1
    For Each item As String In cataList.Items
        'cataList is a listbox
        Cty(i).name = item
        i += 1
    Next

抛出nullReferenceException。

缺少什么?我需要结构是全球性的。

2 个答案:

答案 0 :(得分:1)

cataList.Items由listviewitems而不是字符串组成。这可能会导致问题。另外,Cty在声明时没有成员。

试试这个:

ReDim Cty(cataList.Items.Count-1)

For Each item As ListViewItem In cataList.Items
    'cataList is a listbox
    Cty(i).name = item.Text
    i += 1
Next

您也可以使用列表(使用.add)而不是数组来避免重新开始。

答案 1 :(得分:1)

您的数组已声明但未实例化,因为链接的dupe描述。但是,一系列结构并不是最有效的方法。

Friend Class Ct                     ' cries out for a meaningful name        

    Public Property Name As String
    Private _identities As New List(of String)    ' ie "Pty"

    ' a ctor to create with the name prop
    Public Sub New(n As String)
        Name = n
    End Sub

    Public Sub AddIdentity(id As String)
         _identities.Add(id)
    End Sub

    ' get one
    Public Function GetIdentity(index As Integer) As String
         Return _identities(index)
    End Sub

    ' get all
    Public Function Identities As String()
        Return _identities.ToArray
    End If

    ' and so on for Count, Clear...  
End Class

然后列出这些事情:

' as (elegantly) described in the NRE link, NEW creates an instance:
Friend Cty As New List(Of Ct)            

然后从ListBox填充List:

For Each s As String In cataList.Items
    Cty.Add(New CT(s))             ' create CT with name and add to list
Next

您使用列表和收藏集的次数越多,您就会越了解它们的灵活性和强大程度。例如,可能根本不需要手动填充ListBox。使用DataSource属性将列表绑定到列表框;这样更有效,因为你映射而不是数据复制到UI控件:

' tell the listbox which property on your class (Type) to display
cataList.DisplayMember = "Name"
cataList.DataSource = Cty  

对于您需要/需要复制数据的情况:

For n As Integer = 0 to Cty.Count-1
    cataList.Items.Add(Cty(n).Name)
Next

或者:

For Each item As Ct In cty          
    cataList.Items.Add(item.Name)
Next