Given this class
public class Foo
{
public string Name { get; set; }
}
This method (in some other class)...
private Func<Foo, string> Compile(string body)
{
ParameterExpression prm = Expression.Parameter(typeof(Foo), "foo");
LambdaExpression exp = DynamicExpressionParser.ParseLambda(new[] { prm }, typeof(string), body);
return (Func<Foo, string>)exp.Compile();
}
Will take the right hand side of a lambda expression and give me back a delegate. So if it is called like this:
Foo f = new Foo { Name = "Hamilton Academicals" };
//foo => foo.Name.Substring(0,3)
Func<Foo, string> fn = Compile("foo.Name.Substring(0,3)");
string sub = fn(f);
Then sub will have the value "Ham".
All well and good, however, I would like to make Foo subclass DynamicObject (so that I can implement TryGetMember to dynamically work out property values), so I want to take the expression and get the equivalent of this
Func<dynamic, dynamic> fn = foo => foo.Name.Substring(0,3);
I've tried Expression.Dynamic using a custom CallSiteBinder, but that fails with No property or field Bar exists in type Object (when I try to access foo.Bar dynamically). I'm assuming that is because the call to get foo.Bar needs to be dynamically dispatched (using Expression.Dynamic), but that isn't going to work for me because a key aim is that a user can enter a simple expression and have it executed. Is it possible?