.net - VB.NET需要一个class属性才能成为列表数组

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

堆放过量鲜花:

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

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

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

最佳答案

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

在您的Accessory类的构造函数中对其进行初始化。就像是

Public Sub New()
    _items = New List(Of Item)
End Sub

关于.net - VB.NET需要一个class属性才能成为列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1564318/

相关文章:

c# - 为什么 SortedSet<T>.GetViewBetween 不是 O(log N)?

c# - 使用自动刷新完成自定义 TraceListener ='false'(C#、.net)

c# - SqlCommandBuilder.DeriveParameters 有多贵?

asp.net - 在 Asp.Net MVC 2 应用程序中使用 jquery 确认删除链接

asp.net - 在 ASP.net 页面中嵌入 SVG

vb.net - AccessViolationException 未处理?

c# - 是否有开箱即用的方法来反序列化 Json.Net 中的抽象类?

c# - 如何在 ASP.NET 和 C# 中的网格中显示树结构?

vb.net - COM 与非 COM DLL

vb.net - 如何在没有 IDispatch 的情况下创建 VB.NET COM 可见接口(interface)?