【问题标题】:what is the Linq expression tree for setting a property of an object?什么是用于设置对象属性的 Linq 表达式树?
【发布时间】:2011-10-07 22:53:10
【问题描述】:

假设我有:

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

【问题讨论】:

  • 作为警告,您至少需要 .Net 4.0。

标签: c# linq .net-4.0 expression-trees


【解决方案1】:

这是一个例子。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多