我有一些沉重的方法,像这样:
public static int GetCoord(int coord)
{
Thread.Sleep(10000);
return coord;
}
以及使用此方法的表达式:
private static readonly Expression<Func<Point>> Calculate = () => new Point
{
X = GetCoord(1),
Y = GetCoord(1)
};
如您所见,此表达式调用了两次重载方法,因此我想优化此表达式。我有一个想法,删除Y的第二个顶点并添加边,但是在实现它时遇到了一些麻烦。我这样使用ExpressionVisitor:
public class ExpressionOptimizer : ExpressionVisitor
{
readonly Dictionary<string, Expression> methodCallExpressions = new Dictionary<string, Expression>();
public Expression Optimize(Expression expression)
{
return Visit(expression);
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var debugViewPropertyInfo = typeof(Expression).GetProperty("DebugView", BindingFlags.Instance | BindingFlags.NonPublic);
var debugViewValue = debugViewPropertyInfo.GetValue(node) as string;
if (methodCallExpressions.TryGetValue(debugViewValue, out Expression expression))
{
return expression;
}
methodCallExpressions.Add(debugViewValue, node);
return base.VisitMethodCall(node);
}
}
但是此解决方案调用方法两次。我能以某种方式实现我的想法吗?