I want to use type returned by PropertyType to create a typed function. I found this similiar
using type returned by Type.GetType() in c#
but this mentions how to create a list but does not mention how we can create a Func<>. Please help me out.
Pseudocode:
PropertyInfo inf = typeof(SomeClass).GetProperty("PropertyName");
Type T=inf.PropertyType;
Expression<Func<SomeClass,T>> le = GetPropertyOrFieldByName<SomeClass,T>("PropertyName");
static Expression<Func<TSource, TResult>> GetPropertyOrFieldByName<TSource,TResult>(string propertyOrFieldName)
{
ParameterExpression item = Expression.Parameter(typeof(TSource), "expr");MemberExpression prop = LambdaExpression.PropertyOrField(item, propertyOrFieldName);
var expr = Expression.Lambda<Func<TSource, TResult>>(prop, new ParameterExpression[] { item });
expr.Compile();
return expr;
}
If you want to call the
GetPropertyOrFieldByNamewith thePropertyType, this should work:Assuming that the
GetPropertyOrFieldByNamemethod is a public static method.