开发者

Transfer object of 1 type to object of a different type

开发者 https://www.devze.com 2022-12-18 14:47 出处:网络
I\'m trying to create a transfer mechanism where I can take a Class Object and convert it to a webservice object, with minimal amount of code.

I'm trying to create a transfer mechanism where I can take a Class Object and convert it to a webservice object, with minimal amount of code.

I've had pretty good success with this approach but I need to refine the techinque for when I have custom Classes being returned as properties off my source object.

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

What I need is some what of Determining if the Source Property is a Basic Type (string,开发者_开发问答 int16, int32 etc, and not of Complex type).

I was looking at the s.PropertyType.Attributes and checking the masks on that, but I can't seem to find anything that indicates it is a base type.

Is there something I can check to find this out?


With thanks for the tip from abmv, this is the final result I endedup using. I still needed to code in a few specific properties, but most of them were dealt with automatically via this mechanism.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号