首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

.NET Framework 4.0 Beta 1 中的 Expression Tree 實作範例

     編輯:關於ASP.NET

安裝 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 發展。

背景

  • DLR 代碼快速變動中,ETv2 作為 LINQ 與 DLR 共用部分放入標準庫
  • 折中方案:標準庫版本移除 DLR 尚未穩定與低優先級功能
  • LoopExpression 進入標準庫,但 ForEach、While 特化版本僅在 CodePlex DLR 版本有

命名空間與組件

  • .NET 4.0:System.Core.dll、System.Linq.Expressions
  • CodePlex DLR:Microsoft.Scripting.Core.dll、Microsoft.Linq.Expressions(避免衝突,但導致編譯器產生的 ET 與 DLR ET 不相容)

實作範例:以 ETv2 建構遍歷並輸出 LINQ 查詢結果的委派

程式碼截圖

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。最後編譯並執行委派。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved