copy one object to another

后端 未结 2 1728
悲&欢浪女
悲&欢浪女 2021-01-07 11:53

.net 3.5, VS 2010... this is for an asp.net website.

I have an class called Agency. there is a second class called Agency_Queries. Agency_Queries inhertis the Agen

相关标签:
2条回答
  • 2021-01-07 12:26

    I took a little of this and that and came up with this:

        Imports System.Reflection
    
    Public Class ObjectHelper
    
        ' Creates a copy of an object
        Public Shared Function GetCopy(Of SourceType As {Class, New})(ByVal Source As SourceType) As SourceType
    
            Dim ReturnValue As New SourceType
            Dim sourceProperties() As PropertyInfo = Source.GetType().GetProperties()
    
            For Each sourceProp As PropertyInfo In sourceProperties
                sourceProp.SetValue(ReturnValue, sourceProp.GetValue(Source, Nothing), Nothing)
            Next
            Return ReturnValue
        End Function
    End Class
    
    0 讨论(0)
  • 2021-01-07 12:34

    I use the following:

    <Extension>
    Public Sub CopyPropertiesByName(Of T1, T2)(dest As T1, src As T2)
    
      Dim srcProps = src.GetType().GetProperties()
      Dim destProps = dest.GetType().GetProperties()
    
      For Each loSrcProp In srcProps
        If loSrcProp.CanRead Then
          Dim loDestProp = destProps.FirstOrDefault(Function(x) x.Name = loSrcProp.Name)
          If loDestProp IsNot Nothing AndAlso loDestProp.CanWrite Then
            Dim loVal = loSrcProp.GetValue(src, Nothing)
            loDestProp.SetValue(dest, loVal, Nothing)
          End If
        End If
      Next
    End Sub
    
    0 讨论(0)
提交回复
热议问题