2011-09-07 77 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