用文本文件填充结构

时间:2019-04-28 18:45:45

标签: vb.net

我试图用“ stockInventory.txt”的内容填充“ Stock” 我收到错误消息“ System.NullReferenceException:'对象引用未设置为对象的实例。'

storeInven没什么。

在“表单加载事件”中,我有一个循环,我认为该循环会填充其中包含“股票”的数组的索引0。

Public Class Form1
Structure Stock
    Public category As String
    Public price As Integer
    Public size As String
    Public sku As String
    Public color As String
End Structure

Dim stockArray() As String =
       IO.File.ReadAllLines("stockInventory.txt")

Dim storeInven() As Stock

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim inFile As System.IO.StreamReader
    inFile = New IO.StreamReader("stockInventory.txt")
    If IO.File.Exists("stockInventory.txt") Then

        Dim upperbound As Integer = stockArray.GetUpperBound(0)

        For i As Integer = 0 To upperbound

            storeInven(i).category = stockArray(0)
            storeInven(i).price = CInt(stockArray(1))
            storeInven(i).size = CInt(stockArray(2))
            storeInven(i).sku = stockArray(3)
            storeInven(i).color = stockArray(4)

        Next i
    End If
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

创建的storeInven()数组没有元素。因此,storeInven(i)没有元素。您有一个名为storeInven的对象引用变量,它没有设置为对象的实例。

.Net使用的是 real 数组,而不是您在其他平台(如PHP或javascript)中看到的类似数组的集合。 .Net也有集合,但是当您请求数组时,您会得到一个真实数组。关于真实数组的一件事是它们具有固定大小。您很有可能真的要在这里List(Of Stock),而不是数组。

Public Class Form1

    Structure Stock
        Public category As String
        Public price As Integer
        Public size As String
        Public sku As String
        Public color As String
    End Structure

    Dim storeInven As List(Of Stock)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim stockArray() As String =
            IO.File.ReadAllLines("stockInventory.txt")

        storeInven = New List(Of Stock)   
        storeInven.Add(New Stock() With {
            category = stockArray(0),
            price = CInt(stockArray(1)),
            size = CInt(stockArray(2)),
            sku = stockArray(3),
            color = stockArray(4)
         })    
    End Sub
End Class