Last active
August 29, 2015 14:20
-
-
Save duncansmart/810b6117998d17374f2c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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