Eri*_*ric 5 c# linq .net-4.0 expression-trees
假设我有:
class Foo {
public int Bar { get; set; }
}
public void SetThree( Foo x )
{
Action<Foo, int> fnSet = (xx, val) => { xx.Bar = val; };
fnSet(x, 3);
}
Run Code Online (Sandbox Code Playgroud)
如何使用表达式树重写fnSet的定义,例如:
public void SetThree( Foo x )
{
var assign = *** WHAT GOES HERE? ***
Action<foo,int> fnSet = assign.Compile();
fnSet(x, 3);
}
Run Code Online (Sandbox Code Playgroud)
这是一个例子.
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; }
}
Run Code Online (Sandbox Code Playgroud)
打印出"3".
归档时间: |
|
查看次数: |
2240 次 |
最近记录: |