开发者

Null reference but it's not?

开发者 https://www.devze.com 2023-01-01 18:51 出处:网络
This is related to my previous question but it is a different problem. I have two classes: Server and Database.

This is related to my previous question but it is a different problem.

I have two classes: Server and Database.

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

Fairly simple. I use like this:

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

The problem is in the LoadTables in the Server class. When it hits Databases.Add(db) it gives me a NullReference error (Object reference not set). I don't understand how it is getting that, all the obje开发者_开发技巧cts are set. Any ideas? Thanks.


Databases is null.

Change it to

Private _databases As New List(Of Database)


You haven't actually created the list that you are attempting to add the object to. You've only created the property and it's backing property. You need to instantiate the list and assign it, typically in the constructor, or as part of the declaration.

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


I can't see where the _databases private field is being initiated, as it stands it is a null pointer.


Take a close look at the code for the Databases 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

The getter here simply returns the field _databases. This field is defined but never initialized hence it is Null/Nothing. Try changing the field to

Private _databases As New List(Of Database)
0

精彩评论

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