C# 表达式树修改问题
我有以下资料:C# 表达式树修改问题,c#,expression-trees,C#,Expression Trees,我有以下资料: Expression<Func<Car, int>> myExpr = car => car.Wheel.Tyre.Pressure; 或 表达式anotherExpr=car=>car.Wheel.GetTyre().GetPressure(); 我怎样才能优雅地做到这一点 谢谢 Andrew您签出了它的可编辑表达式吗?从 然后加入这段代码,我认为您有了一个解决方案(测试内容是我如何测试它的,我认为它与您所做的几乎相同): 类测试 { 公开考试
Expression<Func<Car, int>> myExpr = car => car.Wheel.Tyre.Pressure;
或
表达式anotherExpr=car=>car.Wheel.GetTyre().GetPressure();
我怎样才能优雅地做到这一点
谢谢
Andrew您签出了它的可编辑表达式吗?从
然后加入这段代码,我认为您有了一个解决方案(测试内容是我如何测试它的,我认为它与您所做的几乎相同):
类测试
{
公开考试()
{
表达式trim2=s=>s.Substring(1).Substring(1);
var modifier=新的PopModifier();
表达式trim1=(表达式)修饰符.Modify(trim2);
var test2=trim2.Compile();
var test1=trim1.Compile();
var input=“abc”;
如果(测试2(输入)!=“c”)
{
抛出新异常();
}
如果(测试1(输入)!=“bc”)
{
抛出新异常();
}
}
}
公共类PopModifier:ExpressionVisitor
{
bool-diddmodify=false;
公共表达式修改(表达式)
{
回访(表达);
}
受保护的重写表达式VisitMethodCall(MethodCallExpression m)
{
如果(!didModify)
{
didModify=true;
返回m.对象;
}
返回基。访问方法调用(m);
}
}
不,我没有,但如果这是一半的话,我已经有了一百万个它的用途,这将是非常棒的。不错
Expression<Func<Wheel, int>> mySubExpr = wheel => wheel.Tyre.Pressure;
Expression<Func<Car, int>> myOtherExpr = car => car.GetRearLeftWheel().GetTyre().Pressure
Expression<Func<Car, int>> anotherExpr = car => car.Wheel.GetTyre().GetPressure();
class Test
{
public Test()
{
Expression<Func<string, string>> trim2 = s => s.Substring(1).Substring(1);
var modifier = new PopModifier();
Expression<Func<string, string>> trim1 = (Expression<Func<string, string>>)modifier.Modify(trim2);
var test2 = trim2.Compile();
var test1 = trim1.Compile();
var input = "abc";
if (test2(input) != "c")
{
throw new Exception();
}
if (test1(input) != "bc")
{
throw new Exception();
}
}
}
public class PopModifier : ExpressionVisitor
{
bool didModify = false;
public Expression Modify(Expression expression)
{
return Visit(expression);
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
if (!didModify)
{
didModify = true;
return m.Object;
}
return base.VisitMethodCall(m);
}
}