VB.NET 中什么可以被视为实例:未将对象引用设置为对象的实例
我遇到了以下问题。我有一个带有构造函数的类(一个 New(
方法)。我还有一个我想要填充的此类对象的List
。举个例子,这里有一些玩具代码(避免属性等):
Class Thing
Public PositionX, PositionY As UInteger
Public Name As String
Public Sub New(ByVal name As String, _
ByVal positionX As UInteger, _
ByVal positionY As UInteger)
Me.PositionX = positionX
Me.PositionY = positionY
Me.Name = name
End Sub
End Class
此外,在代码的其他地方,我声明了一个 Thing
列表:
Dim things As List(Of Thing)
当尝试运行以下代码行时,things.Add(New Thing("some name', 1, 1))
,我得到一个 Object reference not set to an instance of an object
异常。显然,我有一个对实例的误解 可以追溯到我的 C/C++ 背景。
对象的本质以及 VB.NET 如何使用它们,我想这 当然,我可以使用 New
构造函数初始化一个变量,然后然后将其添加到列表中:
以下内容也不起作用:
Dim myThing = New Thing("some name", 1, 1)
things.Add(myThing)
我的问题是为什么简单地说 New Thing("some name', 1, 1)
并不会创建 Thing
的实例,什么是正确的方法想想我在设计上做错了什么吗?
干杯!
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, _
ByVal 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,您只需要实例化您的列表:
我认为
thing
类的处理一切都很好,但列表也需要一个实例 - 它是一个类/实例,就像事物一样。Looks to me like you just need to instance your list:
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:
or: