Last active
August 29, 2015 14:07
-
-
Save lantoli/c62a8137cf624472329e to your computer and use it in GitHub Desktop.
Refactored ObjectDumper from @eiximenis
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using Dict = System.Collections.Generic.Dictionary<string, System.Delegate>; | |
using Pair = System.Collections.Generic.KeyValuePair<string, string>; | |
namespace ObjectDumper | |
{ | |
public class ObjectDumper<T> where T: class | |
{ | |
private readonly Dict templates = new Dict(); | |
public void AddTemplateFor<TR>(Expression<Func<T, TR>> propExp, Func<TR, string> template) | |
{ | |
templates.Add(((MemberExpression) propExp.Body).Member.Name, template); | |
} | |
public IEnumerable<Pair> Dump(T data) | |
{ | |
if (data == null) yield break; | |
foreach (var property in data.GetType().GetProperties().Where(p => p.CanRead).OrderBy(p=>p.Name)) { | |
var valueProp = property.GetValue(data); | |
Delegate template; | |
var value = templates.TryGetValue(property.Name, out template) | |
? template.DynamicInvoke(valueProp) as string | |
: Convert.ToString(valueProp); | |
yield return new Pair(property.Name, value); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment