【问题标题】:What can be considered an instance in VB.NET: Object reference not set to an instance of an object在 VB.NET 中什么可以被视为实例:对象引用未设置为对象的实例
【发布时间】:2011-08-10 09:18:26
【问题描述】:

我遇到了以下问题。我有一个带有构造函数的类(New(<args>) 方法)。我还有一个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

另外,我在代码的其他地方声明了Things 的列表:

Dim things As List(Of Thing)

当尝试运行以下代码行things.Add(New Thing("some name', 1, 1)) 时,我得到了Object reference not set to an instance of an object 异常。显然,我对对象实例的真正含义以及 VB.NET 如何使用它们存在误解。我想这可以追溯到我的 C/C++ 背景。

当然,我可以使用New 构造函数初始化一个变量,然后然后将它添加到列表中:

以下也不起作用:

Dim myThing = New Thing("some name", 1, 1)
things.Add(myThing)

我的问题是为什么简单地说New Thing("some name', 1, 1) 不会创建Thing实例 思考这些事情的正确方法是什么?我在设计上做错了什么?

干杯!

【问题讨论】:

    标签: vb.net oop list constructor instance


    【解决方案1】:

    在我看来你只需要实例化你的列表:

    Dim things As New List(Of Thing)
    

    我认为 thing 类的处理一切都很好,但列表也需要一个实例 - 它是一个类/实例,就像事情一样。

    【讨论】:

    • 天啊!我现在觉得很傻=)谢谢! (将在所需的 10 分钟后接受答案)
    【解决方案2】:

    你需要做的:

    Dim things as New List(Of Thing)
    

    或:

    Dim things as List(Of Thing)
    things=New List(Of Thing)
    

    【讨论】:

      猜你喜欢
      • 2013-01-14
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多