微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – 克隆一个列表(类)

我已经做了一些阅读,似乎无法解决在我的VB2010项目中克隆List(类)的最佳方法.我有三个相关的课程

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变量是危险等级列表.我该如何克隆那门课?

解决方法

实现IClonable并不意味着它取代了常规赋值,它仍然只是复制引用.你甚至没有复制项目,你正在复制列表,这意味着你仍然只有一个列表,但有两个列表.

要使用克隆方法,您必须为列表中的每个项目调用它:

rdNew.Hazards = rd.Hazards.Select(Function(x) x.Clone()).Cast(Of Hazard).ToList()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐