下面是结构的定义
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
这是在一个叫做主模块声明。
This is declared in a module called main.
那么这块code,坐落在一个子程序另一类运行
Then this piece of code, located in a subroutine in another class is run
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。
It throws a nullReferenceException.
缺少什么?我需要的结构是全球性的。
What is missing? I need the structure to be global.
您数组宣告但尚未实例化作为链接欺骗描述。但结构数组是不是最有效的方式做你正在努力。
Your array is declared but not instanced as the linked dupe describes. But an array of structures is not the most efficient way to do what you are trying.
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
然后这些事情的清单:
Then a list of these things:
' as (elegantly) described in the NRE link, NEW creates an instance:
Friend Cty As New List(Of Ct)
然后从列表框中填写清单:
Then fill the List from the ListBox:
For Each s As String In cataList.Items
Cty.Add(New CT(s)) ' create CT with name and add to list
Next
你越有列表和集合的工作越多,你就会AP preciate如何更灵活和强大的他们。例如,有可能不是一个需要手动填充列表框
可言。使用数据源
属性绑定列表,列表框;因为你的地图的,而不是这是更有效的复制的数据到UI控件:
The more you work with Lists and Collections, the more you will appreciate how much more flexible and powerful they are. For instance, there might not be a need to manually populate the ListBox
at all. Use the DataSource
property to bind the list to the listbox; this is more efficient because you map rather than copy the data to the UI control:
' tell the listbox which property on your class (Type) to display
cataList.DisplayMember = "Name"
cataList.DataSource = Cty
有关,你想/需要复制的数据情况:
For cases where you want/need to copy the data:
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