如何解决此对象引用错误

时间:2013-05-17 15:14:35

标签: .net vb.net

我有以下两个课程

Public Class Square
Private _ParentForm As Form
        Public Sub New(ByVal Parent As Form)
            _ParentForm = Parent
        End Sub

    'Implementation omitted

End Class


Public Class Board
    Private _ParentForm As Form

    Public Sub New(ByVal Parent As Form)
        _ParentForm = Parent
    End Sub

    Private _Squares As List(Of Square)

    Public Property Squares() As List(Of Square)
        Get
            Return _Squares
        End Get
        Set(ByVal value As List(Of Square))
            _Squares = value
        End Set
    End Property

End Class

当我使用followng代码时,它会将Object引用设置为对象错误的实例

  Dim b As New Board(Me)
  Dim s As New Square(Me)
  b.Squares.Add(s)

这里发生了什么

2 个答案:

答案 0 :(得分:1)

您没有Square的实例,b.Squares尚未初始化。你需要

b.Squares As New List(Of Square)

然后您可以添加b.Squares.Add(s)

答案 1 :(得分:1)

您尚未初始化_Squares字段。不记得究竟如何在VB上做,但应该是这样的:

Private _Squares As New List(Of Square)

Darren的回答也是对的,但是对于这个,你不必担心在课堂外初始化列表。