Skip to content

Instantly share code, notes, and snippets.

@garystanford
Created August 2, 2014 22:54
Show Gist options
  • Save garystanford/36932d38a785272ee907 to your computer and use it in GitHub Desktop.
Save garystanford/36932d38a785272ee907 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json;
using System.Reflection;
using System.Collections;
namespace ConsoleApplication25
{
class Program
{
public class SourceInnerData
{
public int Id { get; set; }
public string Data { get; set; }
public string ExtraData { get; set; }
}
public class Source
{
public int Id { get; set; }
public string Name { get; set; }
public string ExtraData { get; set; }
public ICollection<SourceInnerData> InnerData { get; set; }
}
public class DestInnerData
{
public int Id { get; set; }
public string Data { get; set; }
}
public class Destination
{
public int Id { get; set; }
public string Name { get; set; }
public List<DestInnerData> InnerData { get; set; }
}
static void Main(string[] args)
{
var c = new Copier();
var src = new Source() { Id = 1, Name = "TestSource", ExtraData = "Blah", InnerData = new List<SourceInnerData>() { new SourceInnerData() { Id = 2, Data = "Inner Data" } } };
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
var dest = c.SerializeCopy<Destination>(src);
}
sw.Stop();
Console.WriteLine("Serialize elapsed: {0}", sw.Elapsed);
sw.Restart();
for (int i = 0; i < 1000000; i++)
{
var refl = c.ReflectionCopy<Destination>(src);
}
sw.Stop();
Console.WriteLine("Reflection elapsed: {0}", sw.Elapsed);
}
public class Copier
{
public TDest ReflectionCopy<TDest>(object srcVal)
where TDest : class, new()
{
if (srcVal == null) { return null; }
TDest dest = new TDest();
var props = srcVal.GetType().GetProperties();
foreach (PropertyInfo p in props)
{
PropertyInfo objPf = typeof(TDest).GetProperty(p.Name);
if (objPf != null)
{
if (objPf.PropertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(objPf.PropertyType))
{
var destCollType = objPf.PropertyType.GenericTypeArguments[0];
var recurse = this.GetType().GetMethod("ReflectionCopy").MakeGenericMethod(destCollType);
IEnumerable srcList = (IEnumerable)p.GetValue(srcVal);
IList destlst = (IList)Activator.CreateInstance(objPf.PropertyType);
foreach(var srcListVal in srcList)
{
var destLstVal = recurse.Invoke(this, new object[1] { srcListVal });
destlst.Add(destLstVal);
}
objPf.SetValue(dest, destlst);
continue;
}
if (p.PropertyType == objPf.PropertyType)
{
objPf.SetValue(dest, p.GetValue(srcVal));
}
}
}
return dest;
}
public TDest SerializeCopy<TDest>(object srcVal)
where TDest : class, new()
{
if (srcVal == null) { return null; }
var temp = JsonConvert.SerializeObject(srcVal);
return JsonConvert.DeserializeObject<TDest>(temp);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment