Suppose I have:
class Foo {
public int Bar { get; set; }
}
public void SetThree( Foo x )
{
Action<Foo, int> fnSet = (xx, val) => { xx.Bar = val; };
fnSet(x, 3);
}
How can I rewrite the definition of fnSet using an expression trees, e.g.:
public void SetThree( Foo x )
{
var assign = *** WHAT GOES HERE? ***
Action<foo,int> fnSet = assign.Compile();
fnSet(x, 3);
}
Here's an example.
void Main()
{
var fooParameter = Expression.Parameter(typeof(Foo));
var valueParameter = Expression.Parameter(typeof(int));
var propertyInfo = typeof(Foo).GetProperty("Bar");
var assignment = Expression.Assign(Expression.MakeMemberAccess(fooParameter, propertyInfo), valueParameter);
var assign = Expression.Lambda<Action<Foo, int>>(assignment, fooParameter, valueParameter);
Action<Foo,int> fnSet = assign.Compile();
var foo = new Foo();
fnSet(foo, 3);
foo.Bar.Dump();
}
class Foo {
public int Bar { get; set; }
}
Prints out "3".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With