0

在构造函数或类变量定义区域中创建列表对象更好吗?他们最终会做同样的事情吗?什么时候一种方法优于另一种方法?

这是一个示例类定义:

Public Class CProject

    'Variable to hold a list of Load Objects, Instantiate here vs in New().
    Private m_LoadList As New List(Of CLoad)

    Public Property LoadList() As List(Of CLoad)
        Get
            Return m_LoadList
        End Get
        Set(ByVal value As List(Of CLoad))
            m_LoadList = value
        End Set
    End Property

    Public Sub New()

    End Sub

End Class

诗句:

Public Class CProject

    'Variable to hold a list of Load Objects
    Private m_LoadList As List(Of CLoad)

    Public Property LoadList() As List(Of CLoad)
        Get
            Return m_LoadList
        End Get
        Set(ByVal value As List(Of CLoad))
            m_LoadList = value
        End Set
    End Property

    Public Sub New()
        m_LoadList = New List(Of CLoad)
    End Sub

 End Class
4

1 回答 1

0

它更接近选项#2,但有一些变化:

Private m_LoadList As List(Of ADR) = Nothing


Public Property LoadList() As List(Of CLoad)
    Get
        If m_LoadList Is Nothing Then
            m_LoadList = New List(Of CLoad)
        End If
        Return m_LoadList
    End Get
    Set(ByVal value As List(Of CLoad))
        m_LoadList = value
    End Set

End Property

这样您就可以引用该属性,并且仅在不存在时才创建新实例。更简单的编码,产生开销的错误机会更少..

于 2013-04-01T12:42:54.020 回答