Generic Object Property Binding
I'm consuming a web service from a third party. I've created a wrapper around that service so that I can expose only the methods I want, and also to perform input validation, etc. So what I'm trying to accomplish is a generic way to map the classes I'm exposing to their counterpart classes from the web service.
For example, the web service has an AddAccount(AccountAddRequest request)
method. In my wrapper, I expose a method called CreateAccount(IMyVersionOfAccountAddRequest request)
, and then I can perform anything I want to do before actually building out the AccountAddRequest
that the web service is expecting.
I'm looking for a way to iterate through all the public properties in my classes, determining if there's a matching property in the web service's version and if so, assign the value. If there's no matching property, then it just gets skipped.
I know this can be accomplished via reflection, but any articles or if there's a specific name to what I'm trying to do开发者_JAVA百科, it would be appreciated.
Copy & paste time!!
Here is one I use in a project to merge data between objects:
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);
}
}
}
}
If you notice the Where
clause I left in there, it is to exclude a specific property from making the list. I've left it in so that you can see how to do it, you may have a list of properties that you want to exclude for whatever reason.
You will also notice that this was done as an extension method, so I can use it like this:
myTargetObject.MergeFrom(someSourceObject);
I don't believe there is any real name given to this, unless you want to use 'cloning' or 'merging'.
精彩评论