VB.NET需要一个类属性作为列表数组

时间:2009-10-14 05:02:18

标签: .net asp.net vb.net arrays class

Stack Overflowers:

我一直绞尽脑汁试图让List(of T)类型数组成为类的属性。我知道必须有一个简单的方法,我在谷歌上找不到一个好的例子。每次我创建一个我认为可以工作的类时,当我尝试使用它时,我得到“对象引用没有设置为对象的实例”错误。我现在的想法是,我不能按照我希望的方式使用它。这是我最近的尝试:

Public Class Item
    Private _itemno As String
    Public Property ItemNo() As String
        Get
            Return _itemno
        End Get
        Set(ByVal value As String)
            _itemno = value
        End Set
    End Property
        //Many more properties in here
End Class


Public Class Accessory
    Private _items as List(of Item)
    Public Property Items() As List(of Item)
        Get
            Return _itemno
        End Get
        Set(ByVal value As List(of Item))
            _itemno = value
        End Set
    End Property
End Class

Public Class MasterItem
    Private _item as Item
    Public Property PrimaryItem as Item
        Get
            Return _item
        End Get
        Set(ByVal value As Item)
            _item = value
        End Set
    End Property

    Private _accessories as Accessory
    Public Property Accessories() As Accessory
        Get
            Return _accessories
        End Get
        Set(ByVal value As Accessory)
            _accessories = value
        End Set
    End Property
End Class

我试图从这样的测试函数返回MasterItem类:

Public Shared Function GetItem() as MasterItem
    Dim testItem as new MasterItem

    ReturnItem.PrimaryItem.ItemNo = "TEST123"

    ReturnItem.Accessories.Items.add(New Item("TESTACC1"))
    ReturnItem.Accessories.Items.add(New Item("TESTACC2"))

    Return testItem
End Function

我在这里做错了什么?提前谢谢。

3 个答案:

答案 0 :(得分:13)

您尚未创建要将项目放入的列表实例。

在Accessory类的构造函数中初始化它。像

这样的东西
Public Sub New()
    _items = New List(Of Item)
End Sub

答案 1 :(得分:1)

您有两个选项可以避免NullReferenceException:

1)方法elder_george提到,您将属性初始化为该类的新实例:

Dim ReturnItem As New MasterItem
ReturnItem.PrimaryItem = New Item()
' or check for null then initialize (optional, depends on your needs)
If ReturnItem.PrimaryItem Is Nothing Then ReturnItem.PrimaryItem = New Item()

这种方法的问题是如果你没有在某个地方初始化它,你知道它以后总是有效,你必须做同样的检查和/或初始化。 “某处”可能是表格负载等。

2)初始化属性的后备存储变量。这样做一次,你不需要一直检查null。请注意以下_item声明中的更改:

Public Class MasterItem
    Private _item as Item = New Item()
    Public Property PrimaryItem as Item
        Get
            Return _item
        End Get
        Set(ByVal value As Item)
            _item = value
        End Set
    End Property
End Class

完成上述操作后,您可以直接访问:

Dim ReturnItem As New MasterItem
ReturnItem.PrimaryItem.ItemNo = "TEST123"

答案 2 :(得分:0)

尝试这样的事情..

Public Class ActiveInfo
    Private _services As List(Of ActiveService)

    Public Sub New()
        _services = New List(Of ActiveService)
    End Sub
    Public Property Services() As List(Of ActiveService)
        Get
            Return _services
        End Get
        Set(ByVal value As List(Of ActiveService))
            _services = value
        End Set
    End Property
End Class

这对我很好......