在构造函数或类变量定义区域中创建List对象更好吗?他们最终会做同样的事情吗?什么时候一种方法优先于另一种?
以下是类定义的示例:
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
答案 0 :(得分: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
通过这种方式,您可以引用该属性,并且仅在不存在时创建新实例。编码更简单,错误发生的可能性更小......