2010-02-02 64 views
0

我试图创建一个传递机制,我可以将一个类对象并将其转换为具有最少量代码的Web服务对象。将1类型的对象转移到不同类型的对象

我已经用这种方法取得了相当不错的成功,但是当我将自定义类作为属性从我的源对象中返回时,我需要优化techinque。

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 

我需要的是确定如果source属性是一个基本类型(字符串,INT16,INT32等,而不是复杂类型)的一些东西。

我在看s.PropertyType.Attributes并检查掩码,但我似乎无法找到任何指示它是基本类型的东西。

有什么我可以检查找出这个?

+0

Type.IsPrimitiveImpl方法 当在派生类中重写,实现了IsPrimitive属性并确定该类型是否是原始类型之一。 http://msdn.microsoft.com/en-us/library/system.type.isprimitiveimpl%28VS.71%29.aspx – abmv 2010-02-02 07:50:52

回答

0

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

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 
相关问题