这是我尝试使用的结构:
Public Structure Point
Public Property id As Integer
Public Property x As Integer
Public Property y As Integer
Public Property Points As List(Of Point)
Public ReadOnly Property key As String
Get
Return x & "," & y
End Get
End Property
Public Sub Add(t As Point)
If Points Is Nothing Then
Points = New List(Of Point)
End If
Points.Add(t)
End Sub
End Structure
下面的代码是尝试使用点结构的尝试:
Dim l = New List(Of Point)
Dim t = new Point 'test point
l.Add(t)
l(l.Count - 1).Add(t)
看l(0).locals窗口中的点,该属性始终为Nothing。
为什么是这样?
已解决:似乎以下代码有效:
Public Structure Point
Public Property id As Integer
Public Property x As Integer
Public Property y As Integer
Private _points As List(Of Point)
Public ReadOnly Property Points() As List(Of Point)
Get
If _points Is Nothing Then
_points = New List(Of Point)
End If
Return _points
End Get
End Property
Public ReadOnly Property key As String
Get
Return x & "," & y
End Get
End Property
Public Sub Add(t As Point)
If _points Is Nothing Then
_points = New List(Of Point)
End If
_points.Add(t)
End Sub
End Structure
用法:
Dim l = New List(Of Point)
Dim t = new Point 'test point
t.add(t)
l.Add(t)
我猜您谈论的错误是NullReferenceException
,解决方案是在使用New
关键字进行访问之前创建实例。
您已经在Add
方法中执行了此操作,但是您应该在构造函数中创建实例。
另外,Class
如果没有充分的理由使用mutable,则应该使用a Structure
。
回应您的编辑:
Dim l = New List(Of Point) Dim t = new Point 'test point l.Add(t) l(l.Count - 1).Add(t)
看l(0).locals窗口中的点,该属性始终为Nothing。
为什么是这样?
这就是为什么我说Structure
如果您没有充分的理由不要使用可变的。
如果你打电话l.Add(t)
,副本的t
将被添加到l
。
当你访问一个Point
通过项目l(l.Count - 1).Add(t)
,创建另一个副本的Point
,再加入另一份的t
到第二个副本。
Add
被称为在第二个副本的t
。当你看l(0)
,你实际看到副本中的第一个副本的t
。
如果这不是您想要的行为,请使用class
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句