以下是我的代码
Class LIVandOSA
Public LIV_ As String
Public OSA_ As String
End Class
Class TestUnitID
Public SMPSdata As LIVandOSA
Public SMdata As LIVandOSA
Public COATEDBARdata As LIVandOSA
Public CLCLdata As LIVandOSA
Public Sub New(ByVal s As String)
SMPSdata.LIV_ = s
End Sub
End Class
在主程序中,我编写了以下代码来创建TestUnitID
列表并在其中添加一些元素。
Dim a As New List(Of TestUnitID)
a.Add(New TestUnitID("a1.csv"))
a.Add(New TestUnitID("a2.csv"))
TextBox1.Text = a(0).SMPSdata.LIV_
但是当我尝试编译它时,它会给我以下错误
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe
Additional information: Object reference not set to an instance of an object.
错误光标指向行SMPSdata.LIV_(s)
我该如何解决此错误?
答案 0 :(得分:2)
错误是不言自明的,您尚未初始化该对象。
由于您在构造函数中,因此它是初始化字段和属性的好地方:
Class TestUnitID
Public SMPSdata As LIVandOSA
Public SMdata As LIVandOSA
Public COATEDBARdata As LIVandOSA
Public CLCLdata As LIVandOSA
Public Sub New(ByVal s As String)
Me.SMPSdata = New LIVandOSA()
Me.SMdata = New LIVandOSA()
Me.COATEDBARdata = New LIVandOSA()
Me.CLCLdata = New LIVandOSA()
SMPSdata.LIV_(s)
End Sub
End Class
答案 1 :(得分:1)
您应该在使用对象之前启动它,因此您可以使用
Me.SMPSdata = New LIVandOSA()
...
创建新对象