Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

c# - variable '' of type '' referenced from scope '', but it is not defined

Well, the following code is self-explaining; I want to combine two expressions into one using And operator. The last line causes rune-time the error:

Additional information: variable 'y' of type 'System.String' referenced from scope '', but it is not defined

Code:

Expression<Func<string, bool>> e1 = y => y.Length < 100;
Expression<Func<string, bool>> e2 = y => y.Length < 200;

var e3 = Expression.And(e1.Body, e2.Body);

var e4 = Expression.Lambda<Func<string, bool>>(e3, e1.Parameters.ToArray());
e4.Compile(); // <--- causes run-time error
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that parameter expression objects that represents variable y in expressions e1 and e2 are different. The fact that the two variables are named the same and have the same type does not matter: e1.Parameters.First() and e2.Parameters.First() is not the same object.

This causes the problem that you see: only e1's parameter y is available to Lambda<>, while e2's parameter y is out of scope.

To fix this problem use Expression APIs to create e1 and e2. This way you would be able to share the parameter expression across them, thus eliminating the problem of scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...