通过索引遍历数组/类索引以复制到另一个索引

时间:2018-10-23 06:17:40

标签: .net vb.net

我找不到确切的搜索词,但是需要一种将一个类的所有元素复制到另一个相同类中的方法。

例如,另一个程序员有一个我必须支持的类似这样的类:

Class Person
    Public Rank AS Integer
    Public Salary As Single
    Public Age As Integer
End Class

所以我写我的代码来处理它,并在需要时将其复制到另一个类。

然后他添加:

Public Height As single

Public Weight As Single

我必须更新所有代码。

我想我记得的是某种语法,它像这样:

For Each Element in Source
    Source.Element.Copy(Target, SizeOf(Element)

我知道没有这样的消息来源,但这是我所要遵循的基本思想,并且要尽可能地回想起我以前看到的所作所为。谁能指出我正确的方向?

1 个答案:

答案 0 :(得分:0)

我正在使用实现ICloneable的基类:

Public Class BaseData
    Implements ICloneable

    Public Overridable Function Clone() As Object Implements ICloneable.Clone
        Dim cloned As Object = Activator.CreateInstance(Me.GetType())

        ' get all public properties
        Dim properties As IEnumerable(Of PropertyInfo) = Me.GetType().GetProperties()

        ' for each property...
        For Each prop In properties
            ' if this property is writable
            If prop.CanWrite Then
                ' get property value
                Dim val As Object = prop.GetValue(Me, Nothing)

                If TypeOf val Is ICloneable Then
                    ' clone the value
                    val = CType(val, ICloneable).Clone()
                ElseIf TypeOf val Is IList AndAlso val.GetType().IsGenericType Then
                    ' clone the list
                    Dim list As IList = Activator.CreateInstance(val.GetType())
                    For Each item In CType(val, IList)
                        If TypeOf item Is ICloneable Then
                            list.Add(CType(item, ICloneable).Clone())
                        Else
                            list.Add(item)
                        End If
                    Next
                    val = list
                End If

                ' assign to cloned
                prop.SetValue(cloned, val, Nothing)
            End If
        Next

        Return cloned
    End Function
End Class

然后我可以使用以下方法获取对象的副本:

Dim copy As Object = original.Clone()