克隆一个列表(类)

时间:2013-01-22 20:30:05

标签: vb.net list class clone icloneable

我已经完成了一些阅读,似乎无法解决在我的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变量是危险等级列表。我将如何克隆那门课程?

3 个答案:

答案 0 :(得分:9)

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

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

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

答案 1 :(得分:1)

Imports System.IO
Imports System.Xml.Serialization        

 Public Function CopyList(Of T)(oldList As List(Of T)) As List(Of T)

            'Serialize
            Dim xmlString As String = ""
            Dim string_writer As New StringWriter
            Dim xml_serializer As New XmlSerializer(GetType(List(Of T)))
            xml_serializer.Serialize(string_writer, oldList)
            xmlString = string_writer.ToString()

            'Deserialize
            Dim string_reader As New StringReader(xmlString)
            Dim newList As List(Of T)
            newList = DirectCast(xml_serializer.Deserialize(string_reader), List(Of T))
            string_reader.Close()

            Return newList
        End Function

答案 2 :(得分:0)

我知道这是旧的。

$text

即使它已经是一个列表,ToList 也会基于它创建一个新列表。

在 VB 2019 中,这将创建一个浅拷贝,但这在某些情况下很有用。这意味着该列表是新的,但 rdNew.Hazards = rd.Hazards.ToList() rd.Hazards 的元素指向同一事物。

如果您编辑任何特定的危害,则会在两者中看到更改。

如果您在一个列表中添加了危害,则另一个列表中将没有。

如果你从一个列表中删除了一个危害,另一个列表中仍然会有它。

如果 Hazard 是原始类型(如字符串或整数),则编辑项将不会反映在其他列表中。

相关问题