【发布时间】:2010-05-16 18:53:38
【问题描述】:
给定以下代码...
class Program {
static void Main(string[] args) {
Foo foo = new Foo { Bar = new Bar { Description= "Martin" }, Name = "Martin" };
DoLambdaStuff(foo, f => f.Name);
DoLambdaStuff(foo, f => f.Bar.Description);
}
static void DoLambdaStuff<TObject, TValue>(TObject obj, Expression<Func<TObject, TValue>> expression) {
// Set up and test "getter"...
Func<TObject, TValue> getValue = expression.Compile();
TValue stuff = getValue(obj);
// Set up and test "setter"...
ParameterExpression objectParameterExpression = Expression.Parameter(typeof(TObject)), valueParameterExpression = Expression.Parameter(typeof(TValue));
Expression<Action<TObject, TValue>> setValueExpression = Expression.Lambda<Action<TObject, TValue>>(
Expression.Block(
Expression.Assign(Expression.Property(objectParameterExpression, ((MemberExpression)expression.Body).Member.Name), valueParameterExpression)
), objectParameterExpression, valueParameterExpression
);
Action<TObject, TValue> setValue = setValueExpression.Compile();
setValue(obj, stuff);
}
}
class Foo {
public Bar Bar { get; set; }
public string Name { get; set; }
}
class Bar {
public string Description{ get; set; }
}
对DoLambdaStuff(foo, f => f.Name) 的调用工作正常,因为我正在访问浅层属性,但是对DoLambdaStuff(foo, f => f.Bar.Description) 的调用失败 - 尽管getValue 函数的创建工作正常,setValueExpression 的创建失败,因为我我正在尝试访问对象的深层属性。
谁能帮我修改这个,以便我可以为深层和浅层属性创建setValueExpression?
谢谢。
【问题讨论】: