static class Extensions { public static Dummy<T> Where<T>(this Dummy<T> dummy, Func<T,bool> predicate) {//声明where扩展方法 //predicate {Method = {Boolean <Main>b__1(System.String)}} System.Func<string,bool> Console.WriteLine("Where called"); return dummy; } } class Dummy<T> { public Dummy<U> Select<U>(Func<T,U> selector) {//selector {Method = {System.String <Main>b__0(System.String)}} System.Func<string,string> //声明Select实例方法 Console.WriteLine("Select called"); return new Dummy<U>(); } } class TranslationExample { static void Main() { var source = new Dummy<string>(); //source Queries.Dummy<string> 调用Dummy Where //创建用于查询的数据源 var query = from dummy in source where dummy.ToString()=="Ignored" select "Anything"; //Queries.Dummy<string> //通过查询表达式来调用方法 } }
查询表达式已经被转译成
var query = source.Where(dummy => dummy.ToString() == "Ignored") .Select(dummy => "Anything");Dummy<T>中没有实现IEnumerable<T>。从查询表达式到"普通"代码转换
并不依赖于它,实际上几乎所有LINQ提供器都把数据显示为IEnumerable<T>
或IQueryable<T>。转译不依赖于任何特定类型而仅仅依赖与方法名称和参数。
转译发生在编译过程初期,以便让编译器来挑选实例方法或者扩展方法。可以认为,
转译是在一个独立的预处理引擎中工作。
输出
Where called
Select called