1
給定一個指向對象圖中屬性的表達式,我想檢索擁有該圖的屬性的實例。我一直在掙扎。當前的代碼只是給了我System.InvalidOperationException:LAMBDA參數不在範圍內使用表達式樹導航並返回擁有屬性的對象
[Test]
public void TestExpression()
{
var person = new Person {Address = {Street = "Bank Street"}, Name = "Joe"};
Expression<Func<Person, object>> exp = p => p.Address.Street;
Assert.AreEqual("Bank Street", exp.Compile().Invoke(person));
var owner = GetPropertyOwner(person, exp);
Assert.AreEqual(owner, person.Address);
}
private object GetPropertyOwner<T>(T root, Expression<Func<T, object>> exp)
{
if (exp.Body is MemberExpression)
{
var member = exp.Body as MemberExpression;
if (member.Expression is MemberExpression)
{
var parentMember = member.Expression as MemberExpression;
//parent member will be {p.Address}
//Now I'm trying to reconstruct an expression that I can combile
var parameterExpression = System.Linq.Expressions.Expression.Parameter(typeof(T), "p");
var lambdaExpression = System.Linq.Expressions.Expression.Lambda(parentMember, parameterExpression);
//Next Linethrows System.InvalidOperationException : Lambda Parameter not in scope
var found = lambdaExpression.Compile().DynamicInvoke(person);
return found;
}
}
return new object();
}
太棒了!當我發現我自己的時候,我只是想貼上解決方案。很高興知道,如果我不這樣做,我將不會被卡住!謝謝 – Max 2010-07-16 12:52:36