【问题标题】:VB.net - Adding to an ArrayListVB.net - 添加到 ArrayList
【发布时间】:2014-02-12 12:12:55
【问题描述】:

这是我第一次使用ArrayList。我试图添加到BarcodeArray作为数组列表)并且执行失败并显示错误消息:

对象引用未设置为对象的实例。

我的代码如下所示:

'Populate the arrays        
BarcodeArray.Add(txt_Barcode.Text)
CategoryArray.Add(cmb_Categories.Text)
TitleArray.Add(txt_Title.Text)
DescriptionArray.Add(txt_Description.Text)
QuantityArray.Add(txt_Quantity.Text)
RRPArray.Add(txt_RRP.Text)
CostArray.Add(txt_Cost.Text)

执行第 2 行 时会出现此消息。如何从文本框中将文本添加到 ArrayList 而不会出现此错误?

【问题讨论】:

  • BarcodeArray 什么都不是。只需初始化它。暗淡为 new ArrayList()
  • 只是好奇您为什么需要为您列出的每个不同值维护一个单独的 ArrayList。从它们的名称来看,它似乎更适合具有BarcodeCategory 等属性的Product 类。然后您将填充一个List(Of Product),它可以包含每个产品的所有这些值。

标签: arrays vb.net arraylist


【解决方案1】:

您遇到的这个问题是您在使用 ArrayList 之前没有对其进行实例化。你需要做这样的事情来让你的代码工作:

Dim barcodeArray as New ArrayList()
barcodeArray.Add(txt_Barcode.Text)
... etc ...

但在你的情况下,我想我会创建一个新类:

Public Class Product
    Public Property Barcode as String
    Public Property Category as String
    Public Property Title as String
    ... etc ...
End Class

然后我会在这样的代码中使用它:

Dim productList as New List(Of Product)()
productList.Add(new Product() With {
    .Barcode = txt_Barcode.Text,
    .Category = cmb_Categories.Text,
    .Title = txt_Title.Text,
    ... etc ...
})

这将使您可以使用单个 Product 对象而不是单独的 ArrayList 对象,这将是维护的噩梦。

【讨论】:

    【解决方案2】:

    在 .NET 中,您需要先实例化对象,然后才能对其调用方法。示例:

    Dim a As ArrayList
    a.Add(...)           ' Error: object reference `a` has not been set
    

    解决办法是用一个new ArrayList 来初始化变量:

    Dim a As ArrayList
    
    a = New ArrayList()
    a.Add(...)           
    

    或者,或者:

    Dim a As New ArrayList()
    a.Add(...)           
    

    顺便说一句,ArrayList 是一个旧类,主要是为了向后兼容而存在。当您开始一个新项目时,请改用generic List class

    Dim a As New List(Of String)()
    a.Add(...)           
    

    【讨论】:

      【解决方案3】:

      您需要先实例化它,然后才能使用。 第 2 行 中的问题在于它当时是nullVB.NET 中的Nothing),因为它没有被创建

      由于您要添加到列表中的所有值都有相同的类型,即String,我建议您使用List(Of String) 而不是ArrayList

      尝试以下方法:

      Dim BarcodeArray as List(Of String) = New List(Of String)( { txt_Barcode.Text } )
      Dim CategoryArray as List(Of String) = New List(Of String)( { cmb_Categories.Text } )
      ' ...
      ' Same for the other Lists you will need to use
      

      【讨论】:

        猜你喜欢
        • 2015-03-30
        • 1970-01-01
        • 2020-11-08
        • 2012-03-14
        • 1970-01-01
        • 1970-01-01
        • 2019-02-10
        • 2015-08-16
        • 1970-01-01
        相关资源
        最近更新 更多