What can be considered an instance in VB.NET: Object reference not set to an instance of an object
I'm stuck with the following problem. I have a class with a constructor (a New(<args>)
method). I also have a List
of objects of this class that I'd like to populate. To give an example, here's some toy code (avoiding properties and such):
Class Thing
Public PositionX, PositionY As UInteger
Public Name As String
Public Sub New(ByVal name As String, _
ByVal positionX As UInteger, _
ByV开发者_Go百科al positionY As UInteger)
Me.PositionX = positionX
Me.PositionY = positionY
Me.Name = name
End Sub
End Class
Also, elsewhere in code I'm declaring a list of Thing
s:
Dim things As List(Of Thing)
When trying to run the following line of code, things.Add(New Thing("some name', 1, 1))
, I get a Object reference not set to an instance of an object
exception. Clearly, I have a misunderstanding of what an instance of an object really is and how VB.NET goes about working with them. I guess it goes back to my C/C++ background.
Of course, I could initialize a variable with the New
constructor, and then add it to the list:
The following does not work either:
Dim myThing = New Thing("some name", 1, 1)
things.Add(myThing)
My question is why does simply saying New Thing("some name', 1, 1)
does not create an instance of Thing
what what is the right way to think about such things? Anything I'm doing wrong by design?
Cheers!
Looks to me like you just need to instance your list:
Dim things As New List(Of Thing)
I think everything is fine with the handling of the thing
class, but the list needs an instance too - Its a class/instance just like the things are.
You need to do:
Dim things as New List(Of Thing)
or:
Dim things as List(Of Thing)
things=New List(Of Thing)
精彩评论