开发者

What can be considered an instance in VB.NET: Object reference not set to an instance of an object

开发者 https://www.devze.com 2023-02-27 09:55 出处:网络
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\

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 Things:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消