As you know, you can obtain a MethodInfo
from PropertyInfo.GetGetMethod()
. From that, you can use the following to get a Func<object, object>
to retrieve that property. By a similar method, you could return a strongly-typed Func<TObject, TResult>
. For any given MethodInfo
, you should cache the results of this call if you need it more than once since this method is at least an order of magnitude more expensive than calling the resulting delegate.
private static Func<object, object> BuildAccessor(MethodInfo method)
{
ParameterExpression obj = Expression.Parameter(typeof(object), "obj");
Expression<Func<object, object>> expr =
Expression.Lambda<Func<object, object>>(
Expression.Convert(
Expression.Call(
Expression.Convert(obj, method.DeclaringType),
method),
typeof(object)),
obj);
return expr.Compile();
}