2011-09-07 73 views
1

我正在使用來自第三方的Web服務。我已經爲該服務創建了一個包裝器,以便我只能公開我想要的方法,並且還要執行輸入驗證等等。所以我試圖完成的是映射我暴露的類的通用方法他們在Web服務中的對應類。通用對象屬性綁定

例如,網絡服務有一個AddAccount(AccountAddRequest request)方法。在我的封裝中,我公開了一種名爲CreateAccount(IMyVersionOfAccountAddRequest request)的方法,然後在實際構建Web服務期望的AccountAddRequest之前,我可以執行任何我想要執行的操作。

我正在尋找一種方法來遍歷我的類中的所有公共屬性,確定Web服務的版本中是否存在匹配的屬性,如果是,則分配值。如果沒有匹配的屬性,那麼它會被跳過。

我知道這可以通過反射,但任何文章或如果有一個特定的名稱,我想要做什麼,它將不勝感激。

回答

1

複製&粘貼時間!

這是一個我在項目中使用的對象之間的合併數據:

public static void MergeFrom<T>(this object destination, T source) 
{ 
    Type destinationType = destination.GetType(); 
    //in case we are dealing with DTOs or EF objects then exclude the EntityKey as we know it shouldn't be altered once it has been set 
    PropertyInfo[] propertyInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !string.Equals(x.Name, "EntityKey", StringComparison.InvariantCultureIgnoreCase)).ToArray(); 
    foreach (var propertyInfo in propertyInfos) 
    { 
     PropertyInfo destinationPropertyInfo = destinationType.GetProperty(propertyInfo.Name, BindingFlags.Public | BindingFlags.Instance); 
     if (destinationPropertyInfo != null) 
     { 
      if (destinationPropertyInfo.CanWrite && propertyInfo.CanRead && (destinationPropertyInfo.PropertyType == propertyInfo.PropertyType)) 
      { 
       object o = propertyInfo.GetValue(source, null); 
       destinationPropertyInfo.SetValue(destination, o, null); 
      } 
     } 
    } 
} 

如果您發現Where條款我離開那裏,它是從上榜排除特定的屬性。我已經把它留在了這樣你可以看到如何去做,你可能有一個你想排除的屬性列表,無論出於何種原因。

你還會注意到,這樣做是爲擴展方法,這樣我就可以這樣使用它:

myTargetObject.MergeFrom(someSourceObject); 

我不相信這是給這個任何真實姓名,除非你想使用「克隆」或「合併」。

+0

好啊。這正是我需要的。謝謝一堆! – Nate222