空引用但不是吗?

时间:2010-06-02 17:10:16

标签: .net vb.net nullreferenceexception

这与my previous question有关,但这是一个不同的问题。

我有两个类:服务器和数据库。

Public Class Server

Private _name As String
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal value As String)
        _name = value
    End Set
End Property


Private _databases As List(Of Database)
Public Property Databases() As List(Of Database)
    Get
        Return _databases
    End Get
    Set(ByVal value As List(Of Database))
        _databases = value
    End Set
End Property


Public Sub LoadTables()
    Dim db As New Database(Me)
    db.Name = "test"

    Databases.Add(db)

End Sub
End Class

Public Class Database
Private _server As Server

Private _name As String
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal value As String)
        _name = value
    End Set
End Property


Public Property Server() As Server
    Get
        Return _server
    End Get
    Set(ByVal value As Server)
        _server = value
    End Set
End Property


Public Sub New(ByVal ser As Server)
    Server = ser
End Sub
End Class

相当简单。我这样用:

Dim s As New Server
    s.Name = "Test"
    s.LoadTables()

问题出在Server类的LoadTables中。当它命中Databases.Add(db)时,它会给我一个NullReference错误(未设置对象引用)。我不明白它是如何得到的,所有的对象都设置好了。有任何想法吗?感谢。

4 个答案:

答案 0 :(得分:4)

您实际上并未创建尝试将对象添加到的列表。您只创建了属性及其后备属性。您需要实例化列表并分配它,通常在构造函数中,或作为声明的一部分。

Public Sub New()
   Databases = New List(Of Database)
End Sub

答案 1 :(得分:4)

Databases为空。

将其更改为

Private _databases As New List(Of Database)

答案 2 :(得分:2)

我无法看到_databases私有字段的启动位置,因为它是一个空指针。

答案 3 :(得分:2)

仔细查看Databases属性

的代码
Private _databases As List(Of Database)
Public Property Databases() As List(Of Database)
    Get
        Return _databases
    End Get
    Set(ByVal value As List(Of Database))
        _databases = value
    End Set
End Property

此处的getter只返回字段_databases。此字段已定义但从未初始化,因此它为Null / Nothing。尝试将字段更改为

Private _databases As New List(Of Database)