2010-02-02 133 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