copy one object to another

后端 未结 2 1751
悲&欢浪女
悲&欢浪女 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:34

    I use the following:

    
    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
    

提交回复
热议问题