2013-02-26 30 views
1

我有一個類結構是這樣的:合併數據到派生

空間 - > ServiceRequest - > ServiceRequestSystemX

我已經寫回到ServiceRequestSystemX的列表的方法。數據分開保存到空間信息存儲的位置。所以每次我創建一個ServiceRequestSystemX類型的新對象時,我都會調用不同的接口來返回該服務請求的Spatial對象。

現在因爲ServiceRequestSystemX最終從空間衍生,是有一個快速的方法,我可以合併我的空間物體進入我ServiceRequestSystemX對象,而只是有做:

ServiceRequestSystemX.X_Coordinate = Spatial.X_Coordinate; 

我覺得這繁瑣和不必要的。

回答

4

作爲派生類型,ServiceRequestSystemX將已經公開由Spatial類公開的基礎成員。

+0

我知道...我想知道的是,如果我已經有一個ServiceRequestSystemX類型的對象,然後我得到一個單獨的對象類型空間我可以快速合併Spatial到ServiceRequestSystemX莫名其妙嗎? – markp3rry 2013-02-26 11:49:22

+0

我不認爲有一種非常簡單的方法,因爲您不能隱式地將類型**向下繼承層次結構。 – 2013-02-26 11:53:49

0

根據我在第一個答案中的意見,你可以可以嘗試使用反射來將兩個對象合併在一起。但我會稱這是一個骯髒的黑客。

public static class ExtensionMethods 
{ 
    public static TEntity CopyTo<TEntity>(this TEntity OriginalEntity, TEntity NewEntity) 
    { 
     PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties(); 

     foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite)) 
     { 
      if (CurrentProperty.GetValue(NewEntity, null) != null) 
      { 
       CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null); 
      } 
     } 

     return OriginalEntity; 
    } 
} 

此代碼取自另一篇文章發現here

+0

似乎並非如此簡單,希望可能有一個快速的方法調用,但唉!感謝您的幫助。 – markp3rry 2013-02-26 14:09:38

+0

一旦你創建了上面的擴展,你可以使用'MySpatial.CopyTo(MyServiceRequestSystemX)' - 但它只會填充合併兩邊相同的屬性。 – 2013-02-26 14:44:16