加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 07:24:51 所属栏目:百科 来源:网络整理
导读:我已经做了一些阅读,似乎无法解决在我的VB2010项目中克隆List(类)的最佳方法.我有三个相关的课程 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
我已经做了一些阅读,似乎无法解决在我的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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读