安裝 Visual Studio 2010 Beta 1 後嘗試 .NET Framework 4.0 新功能,重點關注 Expression Tree(運算式樹)。.NET 4.0 中稱為 Expression Tree v2 (ETv2),相容 .NET 3.5 LINQ Expression Tree,但源自 DLR Tree 發展。
LoopExpression 進入標準庫,但 ForEach、While 特化版本僅在 CodePlex DLR 版本有System.Core.dll、System.Linq.ExpressionsMicrosoft.Scripting.Core.dll、Microsoft.Linq.Expressions(避免衝突,但導致編譯器產生的 ET 與 DLR ET 不相容)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
static class Program
{
static void Main(string[] args)
{
var list = from i in Enumerable.Range(0, 100)
where i % 9 == 0
orderby i descending
select i;
var vIter = Expression.Variable(typeof(IEnumerator<int>), "iter");
var vI = Expression.Variable(typeof(int), "i");
var lBreak = Expression.Label();
var eForeach = Expression.Lambda<Action>(
Expression.Block(
new[] { vIter, vI },
Expression.Assign(
vIter,
Expression.Call(
Expression.Constant(list),
typeof(IEnumerable<int>).GetMethod("GetEnumerator"))),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(vIter, typeof(IEnumerator).GetMethod("MoveNext")),
Expression.Block(
Expression.Assign(
vI,
Expression.Property(vIter, "Current")),
Expression.Call(
typeof(Console).GetMethod("WriteLine", new[] { typeof(int) }),
new[] { vI })),
Expression.Break(lBreak))),
lBreak)),
new ParameterExpression[0]);
eForeach.Compile()();
}
}
}
程式邏輯:先建立 in-memory LINQ 查詢(0-99 中 9 的倍數遞減),再用 ETv2 手動構建 foreach 迴圈:取得列舉器 → Loop + IfThenElse 判斷 MoveNext → 取 Current → Console.WriteLine → 否則 Break。最後編譯並執行委派。