2011-10-07 90 views
4

假设我有:设置对象属性的Linq表达式树是什么?

class Foo { 
    public int Bar { get; set; } 
} 
public void SetThree(Foo x) 
{ 
    Action<Foo, int> fnSet = (xx, val) => { xx.Bar = val; }; 
    fnSet(x, 3); 
} 

我怎么可以重写使用表达式树的fnSet的定义,例如:

public void SetThree(Foo x) 
{ 
    var assign = *** WHAT GOES HERE? *** 
    Action<foo,int> fnSet = assign.Compile(); 

    fnSet(x, 3); 
} 
+1

您至少需要.Net 4.0作为警告。 – user7116

回答

7

下面是一个例子。

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; } 
} 

打印出“3”。

+1

+1,需要.Net 4.0。 – user7116

相关问题