在阅读了 Jon Skeet 的“奇怪的查询表达式”之后,我尝试了下面的代码。我希望最后的 LINQ 查询转换为int query = proxy.Where(x => x).Select(x => x);
无法编译的,因为Where
返回一个int
. 代码编译并在屏幕上打印“Where(x => x)”,查询设置为 2。永远不会调用 Select,但它需要在那里才能编译代码。怎么了?
using System;
using System.Linq.Expressions;
public class LinqProxy
{
public Func<Expression<Func<string,string>>,int> Select { get; set; }
public Func<Expression<Func<string,string>>,int> Where { get; set; }
}
class Test
{
static void Main()
{
LinqProxy proxy = new LinqProxy();
proxy.Select = exp =>
{
Console.WriteLine("Select({0})", exp);
return 1;
};
proxy.Where = exp =>
{
Console.WriteLine("Where({0})", exp);
return 2;
};
int query = from x in proxy
where x
select x;
}
}