
Public Class City 'here are many fIElds of type string and integer Public Roads As New List(Of Road)End ClassPublic Class Road 'here are many fIElds of type string and integer Public Hazards As New List(Of Hazard)End ClassPublic 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 FunctionEnd Class
所以,假设我有一个我正在研究的城市,有些情况我想要创建,作为基础的一条道路及其危险,然后添加另一条道路,但使用先前的道路危险作为起点然后调整字段.
Dim rd As New Road'add road fIEldsdim hz1 as New Hazard'add hazard fIEldsdim hz2 as New Hazard'add hazard fIElds'add the hazard objects to the roadrd.Hazards.Add(hz1)rd.Hazards.Add(hz2)'add the road to the citymyCity.Roads.Add(rd)'here I want to start a new road based on the old roadDim rdNew As New Road'copy or clone the hazards from old roadrdNew.Hazards = rd.Hazards '<============'over-write some of the hazard fIEldsrdNew.Hazards(0).Description = "temp"
所以我知道复制一个类会复制指针而不是内容.我在危险类中使用了ICloneable接口,但不能说我正确使用它. Hazards变量是危险等级列表.我该如何克隆那门课?
解决方法 实现IClonable并不意味着它取代了常规赋值,它仍然只是复制引用.你甚至没有复制项目,你正在复制列表,这意味着你仍然只有一个列表,但有两个列表.要使用克隆方法,您必须为列表中的每个项目调用它:
rdNew.Hazards = rd.Hazards.Select(Function(x) x.Clone()).Cast(Of Hazard).ToList()总结
以上是内存溢出为你收集整理的vb.net – 克隆一个列表(类)全部内容,希望文章能够帮你解决vb.net – 克隆一个列表(类)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)