使用Reflector查看闭包

第一种:
.Net 3.5 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 闭包
{
    class Program
    {
        static void Main(string[] args)
        {         
            List<Action> arr = new List<Action>();
            for (int i = 0; i < 3; i++)
            {
                arr.Add(()=>{Console.WriteLine(i);});
            }

            foreach (var item in arr)
            {
                item();//输出3,3,3
            }
        }
    }
}

转换为.Net1.0的代码:
[CompilerGenerated]
private sealed class <>c__DisplayClass2
{
    // Fields
    public int i;

    // Methods
    public void <Main>b__0()
    {
        Console.WriteLine(this.i);
    }
}

 
private static void Main(string[] args)
{
    List<Action> arr = new List<Action>();
    Action CS$<>9__CachedAnonymousMethodDelegate1 = null;
    <>c__DisplayClass2 CS$<>8__locals3 = new <>c__DisplayClass2();
    CS$<>8__locals3.i = 0;
    while (CS$<>8__locals3.i < 3)
    {
        if (CS$<>9__CachedAnonymousMethodDelegate1 == null)//在这里只实例化一个对象
        {
            CS$<>9__CachedAnonymousMethodDelegate1 = new Action(CS$<>8__locals3.<Main>b__0);
        }
        arr.Add(CS$<>9__CachedAnonymousMethodDelegate1);
        CS$<>8__locals3.i++;
    }
    foreach (Action item in arr)
    {
        item();
    }
}

第二种:
.Net 3.5 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 闭包
{
    class Program
    {
        static void Main(string[] args)
        {         
            List<Action> arr = new List<Action>();
            for (int i = 0; i < 3; i++)
            {
                int temp = i;
                arr.Add(()=>{Console.WriteLine(temp);});
            }

            foreach (var item in arr)
            {
                item();//输出0,1,2
            }
        }
    }
}

转换为.Net1.0的代码:
[CompilerGenerated]
private sealed class <>c__DisplayClass1
{
    // Fields
    public int temp;

    // Methods
    public void <Main>b__0()
    {
        Console.WriteLine(this.temp);
    }
}

private static void Main(string[] args)
{
    List<Action> arr = new List<Action>();
    for (int i = 0; i < 3; i++)
    {
        <>c__DisplayClass1 CS$<>8__locals2 = new <>c__DisplayClass1(); //在这里实例化了三个对象
        CS$<>8__locals2.temp = i;
        arr.Add(new Action(CS$<>8__locals2.<Main>b__0));
    }
    foreach (Action item in arr)
    {
        item();
    }
}
posted @ 2010-08-01 14:39  再快一点  阅读(420)  评论(0编辑  收藏  举报