从范围``引用的类型''的变量'',但未定义 [英] variable '' of type '' referenced from scope '', but it is not defined
问题描述
以下代码是不言自明的;我想使用 And
运算符将两个表达式组合为一个。最后一行导致符文运行时间错误:
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:
附加信息:从作用域'引用的'System.String'类型的变量'y' ',但未定义
Additional information: variable 'y' of type 'System.String' referenced from scope '', but it is not defined
代码:
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
推荐答案
感谢大家的合作。
@dasblinkenlight指出两个表达式中的两个参数并不相同。原因?好吧,这是编译器的窍门。编译时,它为每个表达式创建一个类,并为每个参数命名,类似于原始名称xxx1,xxx2...。
As @dasblinkenlight pointed out the two parameters in the two expressions are not the same. Reason? Well, it is the compiler trick. When compiling, it creates a class for each expression and name each parameter something like xxx1, xxx2,... completely different from the original names.
以及答案。 Net 4.0以上版本:
And the answer for .Net 4.0+:
这篇关于从范围``引用的类型''的变量'',但未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!