我试图找出为什么我的代码抛出空引用异常。
我正在尝试将对象添加到列表中。该对象可以是4种类型中的一种,我在所讨论的代码之后具有所有定义。此代码位于select case语句
中4个图片框的按钮单击处理程序中以下是有问题的代码
Dim count As Integer = 0
Dim a_component As Object = Nothing
Select Case (p.Name)
Case TranspositorPictureBox.Name
Form2.ShowDialog(Me)
count = TNumericUpDown.Value
a_component = New Transpositor(tempTranspositorDivert)
Case ZonePictureBox.Name
count = ZNumericUpDown.Value
a_component = New Zone()
Case InductionPictureBox.Name
count = IndNumericUpDown.Value
a_component = New Induction()
Case InclinePictureBox.Name
count = IncNumericUpDown.Value
a_component = New Incline()
End Select
For i = 1 To count
Dim newPic As PictureBox = New PictureBox()
newPic.Image = p.Image
newPic.Size = p.Size
newPic.SizeMode = p.SizeMode
sys.Add(a_component)
LayoutFlowLayout.Controls.Add(newPic)
Next
这是类定义。变量sys的类型为TranSorter
Public Class TranSorter
Public width As Integer
Public components As List(Of Object)
Public Sub New(ByVal the_width As Integer)
Me.width = the_width
Me.components = New List(Of Object)
End Sub
Public Sub Add(ByVal next_component As Object)
Me.components.Add(next_component)
End Sub
End Class
Public Class Transpositor
Public length As Integer
Public divert As Object
Public Sub New(ByVal a_divert As Object)
Me.divert = a_divert
Me.length = ComponentLengths.TranspositorLength
Form1.Transpositors += 1
End Sub
End Class
Public Class Zone
Public length As Integer
Public Sub New()
Me.length = ComponentLengths.ZoneLength
Form1.Microzones += 1
End Sub
End Class
Public Class Induction
Public length As Integer
Public Sub New()
Me.length = ComponentLengths.InductionLength
Form1.Inductions += 1
End Sub
End Class
Public Class Incline
Public length As Integer
Public Sub New()
Me.length = ComponentLengths.InclineLength
Form1.Inclines += 1
End Sub
End Class
sys.add行抛出异常。这是我在
中初始化sys的代码Dim sys As TranSorter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
sys = New TranSorter(temp_width)
答案 0 :(得分:1)
我怀疑由于某种原因,你的p.Name不等于你在If子句中检查的四种情况之一。我建议考虑添加一个毯子Else子句和/或检查a_component是否为空,然后再添加它作为额外的预防措施。
Select Case (p.Name)
Case TranspositorPictureBox.Name
Form2.ShowDialog(Me)
count = TNumericUpDown.Value
a_component = New Transpositor(tempTranspositorDivert)
Case ZonePictureBox.Name
count = ZNumericUpDown.Value
a_component = New Zone()
Case InductionPictureBox.Name
count = IndNumericUpDown.Value
a_component = New Induction()
Case InclinePictureBox.Name
count = IncNumericUpDown.Value
a_component = New Incline()
Case Else
Exit Sub ' Function/etc
End Select
if a_component IsNot Nothing Then
For i = 1 To count
Dim newPic As PictureBox = New PictureBox()
newPic.Image = p.Image
newPic.Size = p.Size
newPic.SizeMode = p.SizeMode
sys.Add(a_component)
LayoutFlowLayout.Controls.Add(newPic)
Next
End If
答案 1 :(得分:1)
除非sys为Nothing,否则您的代码不应抛出任何异常 这可能是因为Form_Load事件,您在哪里初始化sys var,不会执行。 只需在行
上设置断点即可轻松检查这种情况 sys = New TranSorter(temp_width)
然后在
上放置另一个断点 sys.Add(a_component)
行并检查sys var是否为