【发布时间】:2013-01-06 04:59:22
【问题描述】:
我已经阅读了一些内容,但似乎无法理解在我的 VB2010 项目中克隆 List(of class) 的最佳方法是什么。我有三个像这样相关的类
Public Class City
'here are many fields of type string and integer
Public Roads As New List(Of Road)
End Class
Public Class Road
'here are many fields of type string and integer
Public Hazards As New List(Of Hazard)
End Class
Public Class Hazard
Implements ICloneable
'here are many fields of type string and integer and double
Public Function Clone() As Object Implements System.ICloneable.Clone
Return Me.MemberwiseClone
End Function
End Class
假设我有一个正在开发的城市,在某些情况下,我想创建一条道路及其危险,然后添加另一条道路,但使用之前的道路危险作为起点,然后调整字段。
Dim rd As New Road
'add road fields
dim hz1 as New Hazard
'add hazard fields
dim hz2 as New Hazard
'add hazard fields
'add the hazard objects to the road
rd.Hazards.Add(hz1)
rd.Hazards.Add(hz2)
'add the road to the city
myCity.Roads.Add(rd)
'here I want to start a new road based on the old road
Dim rdNew As New Road
'copy or clone the hazards from old road
rdNew.Hazards = rd.Hazards '<============
'over-write some of the hazard fields
rdNew.Hazards(0).Description = "temp"
所以我知道复制一个类将复制指针而不是内容。我在危险类中使用了 ICloneable 接口,但不能说我使用正确。 Hazards 变量是 Hazard 类别的列表。我将如何克隆该类?
【问题讨论】:
-
您需要只复制列表,还是还需要复制列表中的每个对象?
-
您似乎想要一个深度克隆?
-
我想要一份完整的副本。换句话说,Hazards 的所有成员都会被复制到新的道路上。 Hazards 包含字符串、双精度数、整数和一个枚举。我认为克隆就是它的名称,因此我不只是指向原始危害类。
标签: vb.net list class clone icloneable