开发者

C# Cloning including Lambda Expression

I've got a Lambda Expression which is a function that does some operation in a previous context. 开发者_运维技巧Consequently, I will need to clone this object and carry over the expression to the new context, but I am concerned that there would be local values carried over into the new expression. I've made an effort to receive parameters into the expression and avoid object local values, so hopefully this is kept to a minimum. However, my question is, is it possible to clone an expression and have its compiled output honor the new object local values and not the old ones?

I can illustrate if that word picture wasn't descriptive enough.

I am operating under the basic assumption that at some level the same Lambda Expression rules are in effect. That is, how Lambda Expressions recognize local variables to the expression's context.

Thank you...


The lambda expression "rules" are part of the c# compiler (or whatever language you are using); the Expression itself has no automatic knowledge of the context. Instead, if you "capture" a variable, i.e. x below:

int x = ...
Expression<Func<Foo, bool>> predicate = obj => obj.Bar == x;

the compiler creates an instance of a generated context class, and uses ConstantExpression to associate it with the tree:

// approximate representative code; not literal translation
var ctx = new SomeContext();
ctx.x = ... // x is actually a public instance field of SomeContext
var param = Expression.Parameter(typeof(Foo), "obj");
var predicate = Expression.Lambda<Func<Foo, bool>>(
     Expression.Equal(
        Expression.PropertyOrField(param, "Bar"),
        Expression.PropertyOrField(Expression.Constant(ctx), "x")
    ), param);

The only way to "swap" context instance would be to rewrite the entire expression, typically via ExpressionVisitor. Also note that nested scopes can lead to more complex scenarios involving chained context objects.

Personally; I doubt you need to worry about this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜