NullReferenceException 未处理 VB.net 带数组的结构
NullReferenceException was unhandled VB.net Structure with Array
Public Class Form1
Structure Crap
Dim CrapA As Integer
Dim CrapB As Single
Dim CrapC() As Long
Private Sub Initialize()
ReDim CrapC(0 To 100)
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Stuff(0 To 2) As Crap
Stuff(0).CrapA = 16
Stuff(1).CrapA = 32
Stuff(2).CrapA = 64
'This is the line where the NullReferenceException is thrown
Stuff(0).CrapC.Initialize()
For x = 0 To 100
Stuff(0).CrapC(x) = x ^ 2
Next x
MsgBox(Stuff(0).CrapA)
MsgBox(Stuff(1).CrapA)
MsgBox(Stuff(2).CrapA)
For x = 0 To 100
MsgBox(Stuff(0).CrapC(x))
Next x
End Sub
End Class
所以这是一个非常简单的程序,但有一个莫名其妙的错误。我想要的只是一个用户定义类型的数组。我正在从 VB6 迁移到 .net,我读过的所有内容(包括 What is a NullReferenceException, and how do I fix it? 是一篇热心的读物)都无济于事。看来我被困在 1999 年了,哈哈。我知道数组 CrapC 是空的,这就是问题所在。
错误发生在这里:
Stuff(0).CrapC.Initialize()
因为 Crap()
包含 Crap
的三个实例,但您从未初始化 CrapC
字段,它是一个 Long()
。所以你可以在 Nothing
(null
) 上调用 Initialize
。在大多数情况下,您根本不需要此方法:"This method is designed to help compilers support value-type arrays; most users do not need this method."
改为使用此数组初始值设定项来获得具有 100 个 longs 的 Long()
:
Stuff(0).CrapC = New Long(99) {}
Public Class Form1
Structure Crap
Dim CrapA As Integer
Dim CrapB As Single
Dim CrapC() As Long
Private Sub Initialize()
ReDim CrapC(0 To 100)
End Sub
End Structure
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Stuff(0 To 2) As Crap
Stuff(0).CrapA = 16
Stuff(1).CrapA = 32
Stuff(2).CrapA = 64
'This is the line where the NullReferenceException is thrown
Stuff(0).CrapC.Initialize()
For x = 0 To 100
Stuff(0).CrapC(x) = x ^ 2
Next x
MsgBox(Stuff(0).CrapA)
MsgBox(Stuff(1).CrapA)
MsgBox(Stuff(2).CrapA)
For x = 0 To 100
MsgBox(Stuff(0).CrapC(x))
Next x
End Sub
End Class
所以这是一个非常简单的程序,但有一个莫名其妙的错误。我想要的只是一个用户定义类型的数组。我正在从 VB6 迁移到 .net,我读过的所有内容(包括 What is a NullReferenceException, and how do I fix it? 是一篇热心的读物)都无济于事。看来我被困在 1999 年了,哈哈。我知道数组 CrapC 是空的,这就是问题所在。
错误发生在这里:
Stuff(0).CrapC.Initialize()
因为 Crap()
包含 Crap
的三个实例,但您从未初始化 CrapC
字段,它是一个 Long()
。所以你可以在 Nothing
(null
) 上调用 Initialize
。在大多数情况下,您根本不需要此方法:"This method is designed to help compilers support value-type arrays; most users do not need this method."
改为使用此数组初始值设定项来获得具有 100 个 longs 的 Long()
:
Stuff(0).CrapC = New Long(99) {}