Created
May 19, 2016 17:34
-
-
Save gowon/60260295e985c1be8f1600671b19822e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://github.com/jakkaj/Xamling-Core/blob/918a7400583774106d5a9fba82a5f14656d52b06/XamlingCore/XamlingCore.Portable/Data/Mapper/SimpleMapper.cs | |
//From: http://stackoverflow.com/questions/930433/apply-properties-values-from-one-object-to-another-of-the-same-type-automaticall | |
//user: http://stackoverflow.com/users/428886/azerothian | |
//with Modifications for PCL by Jordan Knight. | |
using System; | |
using System.Linq; | |
using System.Reflection; | |
namespace XamlingCore.Portable.Data.Mapper | |
{ | |
/// <summary> | |
/// A static class for reflection type functions | |
/// </summary> | |
public static class SimpleMapper | |
{ | |
/// <summary> | |
/// Extension for 'Object' that copies the properties to a destination object. | |
/// </summary> | |
/// <param name="source">The source.</param> | |
/// <param name="destination">The destination.</param> | |
public static void CopyProperties(this object source, object destination) | |
{ | |
// If any this null throw an exception | |
if (source == null || destination == null) | |
throw new Exception("Source or/and Destination Objects are null"); | |
// Getting the Types of the objects | |
var typeDest = destination.GetType(); | |
var typeSrc = source.GetType(); | |
// Collect all the valid properties to map | |
var results = from srcProp in typeSrc.GetRuntimeProperties() | |
let targetProperty = typeDest.GetRuntimeProperty(srcProp.Name) | |
where srcProp.CanRead | |
&& targetProperty != null | |
&& targetProperty.SetMethod != null | |
&& targetProperty.CanWrite | |
&& (targetProperty.SetMethod.Attributes & MethodAttributes.Static) == 0 | |
&& targetProperty.PropertyType.GetTypeInfo().IsAssignableFrom(srcProp.PropertyType.GetTypeInfo()) | |
select new { sourceProperty = srcProp, targetProperty = targetProperty }; | |
//map the properties | |
foreach (var props in results) | |
{ | |
props.targetProperty.SetValue(destination, props.sourceProperty.GetValue(source, null), null); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment