如何使用Linq表达式树设置对象属性?

5
假设我有以下内容:
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
1个回答

8

这里有一个例子。

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"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接