代码之家  ›  专栏  ›  技术社区  ›  Paul Farry

将1类型的对象转移到其他类型的对象

  •  0
  • Paul Farry  · 技术社区  · 15 年前

    我正在尝试创建一种传输机制,在这种机制中,我可以用最少的代码获取一个类对象并将其转换为webservice对象。

    我已经在这种方法上取得了相当好的成功,但是当我有自定义类作为源对象的属性返回时,我需要改进技术。

    Private Sub Transfer(ByVal src As Object, ByVal dst As Object)
        Dim theSourceProperties() As Reflection.PropertyInfo
    
        theSourceProperties = src.GetType.GetProperties(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
    
        For Each s As Reflection.PropertyInfo In theSourceProperties
            If s.CanRead AndAlso (Not s.PropertyType.IsGenericType) Then
                Dim d As Reflection.PropertyInfo
                d = dst.GetType.GetProperty(s.Name, Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
                If d IsNot Nothing AndAlso d.CanWrite Then
                    d.SetValue(dst, s.GetValue(src, Nothing), Nothing)
                End If
            End If
        Next
    End Sub
    

    我需要的是确定源属性是否是基本类型(string、int16、int32等,而不是复杂类型)的一些方法。

    有什么我可以查一下的吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   Paul Farry    15 年前

    感谢abmv的提示,这是我使用endedup的最终结果。我仍然需要编写一些特定属性的代码,但大多数属性都是通过这种机制自动处理的。

    Private Sub Transfer(ByVal src As Object, ByVal dst As Object)
        Dim theSourceProperties() As Reflection.PropertyInfo
    
        theSourceProperties = src.GetType.GetProperties(Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
    
        For Each s As Reflection.PropertyInfo In theSourceProperties
            If s.CanRead AndAlso (Not s.PropertyType.IsGenericType) And (s.PropertyType.IsPrimitive Or s.PropertyType.UnderlyingSystemType Is GetType(String)) Then
                Dim d As Reflection.PropertyInfo
                d = dst.GetType.GetProperty(s.Name, Reflection.BindingFlags.Public Or Reflection.BindingFlags.Instance)
                If d IsNot Nothing AndAlso d.CanWrite Then
                    d.SetValue(dst, s.GetValue(src, Nothing), Nothing)
                End If
            End If
        Next
    End Sub
    
    推荐文章