我试图为一个arrayList分配一个类的实例,但是它给了我以下错误。
Object reference not set to an instance of an object.
这是我分配的代码。
Public memberList As ArrayList
Public Sub LoadUser()
Dim userId As Integer = 0
Dim userData As Data.DataTable = oExecuteSimpleQuery_DT("QA", "SELECT * FROM Member")
If userData IsNot Nothing Then
For Each user As Data.DataRow In userData.Rows
If memberList(userId) Is Nothing Then
memberList(userId) = 1
End If
memberList(userId) = New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))
userId += 1
Next
End If
End Sub
答案 0 :(得分:3)
在您的问题中显示的代码中,您确实声明了memberList
变量,但是您没有创建实例。要解决错误,请将第一行更改为:
Public memberList As New ArrayList()
两个侧节点:
ArrayList
,而是查看List(Of T)
。它提供了几乎相同的功能,但输入结构很强。NullReferenceException
是一个值得理解的常见错误。有关原因和解决方法的详细信息,请参阅此link。答案 1 :(得分:1)
试试这个:
Public memberList as New List(Of clsMember)
Public Sub LoadUser()
Dim userId As Integer = 1
Dim userData As Data.DataTable = oExecuteSimpleQuery_DT("QA", "SELECT * FROM Member")
If userData IsNot Nothing Then
For Each user As Data.DataRow In userData.Rows
memberList.Add(New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))
userId += 1
Next
End If
End Sub