Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duncansmart/810b6117998d17374f2c to your computer and use it in GitHub Desktop.
Save duncansmart/810b6117998d17374f2c to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Concurrent;
using System.Reflection;
static class ReflectionUtil
{
static ConcurrentDictionary<PropertyInfo, Func<object, object>> _propertyGettersCache = new ConcurrentDictionary<PropertyInfo, Func<object, object>>();
public static Func<object, object> CreatePropertyGetter(PropertyInfo property)
{
return _propertyGettersCache.GetOrAdd(property, (prop) =>
{
var instance = Expression.Parameter(typeof(object), "instance");
var block = Expression.Block(
expressions: Expression.Property(Expression.Convert(instance, prop.DeclaringType), prop));
return Expression.Lambda<Func<object, object>>(block, instance).Compile();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment