C#語法糖 聊聊閉包的底層玩法
有朋友好奇為什么將 閉包 歸于語法糖,這里簡單聲明下,C# 中的所有閉包最終都會歸結(jié)于 類 和 方法,為什么這么說,因?yàn)?C# 的基因就已經(jīng)決定了,如果大家了解 CLR 的話應(yīng)該知道, C#中的類最終都會用 MethodTable 來承載,方法都會用 MethodDesc 來承載, 所以不管你怎么玩都逃不出這三界之內(nèi)。
這篇我們就來聊聊C#中的閉包底層原理及玩法,表面上的概念就不說了哈。
一:普通閉包玩法
1. 案例演示
放了方便說明,先上一段測試代碼:
static void Main(string[] args)
        {
            int y = 10;
            Func<int, int> sum = x =>
            {
                return x + y;
            };
            Console.WriteLine(sum(11));
        }剛才也說了,C#的基因決定了最終會用 class 和 method 對 閉包 進(jìn)行面向?qū)ο蟾脑?,那如何改造呢?這里有兩個(gè)問題:
- 匿名方法如何面向?qū)ο蟾脑?/li>
 
方法 不能脫離 類 而獨(dú)立存在,所以 編譯器 必須要為其生成一個(gè)類,然后再給匿名方法配一個(gè)名字即可。
- 捕獲到的 y 怎么辦
 
捕獲是一個(gè)很抽象的詞,一點(diǎn)都不接底氣,這里我用 面向?qū)ο?nbsp;的角度來解讀一下,這個(gè)問題本質(zhì)上就是 棧變量 和 堆變量 混在一起的一次行為沖突,什么意思呢?
- 棧變量
 
大家應(yīng)該知道 棧變量 所在的幀空間是由 esp 和 ebp 進(jìn)行控制,一旦方法結(jié)束,esp 會往回收縮造成局部變量從棧中移除。
- 堆變量
 
委托是一個(gè)引用類型,它是由 GC 進(jìn)行管理回收,只要它還被人牽著,自然就不會被回收。
到這里我相信你肯定發(fā)現(xiàn)了一個(gè)嚴(yán)重的問題, 一旦 sum 委托逃出了方法,這時(shí)局部變量 y 肯定會被銷毀,如果真的被銷毀了, 后續(xù)再執(zhí)行 sum 委托自然就是一個(gè)巨大的bug,那怎么辦呢?
編譯器自然早就考慮到了這種情況,它在進(jìn)行面向?qū)ο蟾脑斓臅r(shí)候,特意為 類 定義了一個(gè) public 類型的字段,用這個(gè)字段來承載這個(gè)局部變量。
2. 手工改造
有了這些多前置知識,我相信你肯定會知道如何改造了,參考代碼如下:
class Program
    {
        static void Main(string[] args)
        {
            int y = 10;
            //Func<int, int> sum = x =>
            //{
            //    return x + y;
            //};
            //面向?qū)ο蟾脑?            FuncClass funcClass = new FuncClass() { y = y };
            Func<int, int> sum = funcClass.Run;
            Console.WriteLine(sum(11));
        }
    }
    public class FuncClass
    {
        public int y;
        public int Run(int x)
        {
            return x + y;
        }
    }如果你不相信的話,可以看下 MSIL 代碼。
.method private hidebysig static 
 void Main (
  string[] args
 ) cil managed 
{
 // Method begins at RVA 0x2050
 // Code size 43 (0x2b)
 .maxstack 2
 .entrypoint
 .locals init (
  [0] class ConsoleApp1.Program/'<>c__DisplayClass0_0' 'CS$<>8__locals0',
  [1] class [System.Runtime]System.Func`2<int32, int32> sum
 )
 IL_0000: newobj instance void ConsoleApp1.Program/'<>c__DisplayClass0_0'::.ctor()
 IL_0005: stloc.0
 IL_0006: nop
 IL_0007: ldloc.0
 IL_0008: ldc.i4.s 10
 IL_000a: stfld int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::y
 IL_000f: ldloc.0
 IL_0010: ldftn instance int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::'<Main>b__0'(int32)
 IL_0016: newobj instance void class [System.Runtime]System.Func`2<int32, int32>::.ctor(object, native int)
 IL_001b: stloc.1
 IL_001c: ldloc.1
 IL_001d: ldc.i4.s 11
 IL_001f: callvirt instance !1 class [System.Runtime]System.Func`2<int32, int32>::Invoke(!0)
 IL_0024: call void [System.Console]System.Console::WriteLine(int32)
 IL_0029: nop
 IL_002a: ret
} // end of method Program::Main
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
 extends [System.Runtime]System.Object
{
 .custom instance void [System.Runtime]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
  01 00 00 00
 )
 // Fields
 .field public int32 y
 // Methods
 .method public hidebysig specialname rtspecialname 
  instance void .ctor () cil managed 
 {
  // Method begins at RVA 0x2090
  // Code size 8 (0x8)
  .maxstack 8
  IL_0000: ldarg.0
  IL_0001: call instance void [System.Runtime]System.Object::.ctor()
  IL_0006: nop
  IL_0007: ret
 } // end of method '<>c__DisplayClass0_0'::.ctor
 .method assembly hidebysig 
  instance int32 '<Main>b__0' (
   int32 x
  ) cil managed 
 {
  // Method begins at RVA 0x209c
  // Code size 14 (0xe)
  .maxstack 2
  .locals init (
   [0] int32
  )
  IL_0000: nop
  IL_0001: ldarg.1
  IL_0002: ldarg.0
  IL_0003: ldfld int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::y
  IL_0008: add
  IL_0009: stloc.0
  IL_000a: br.s IL_000c
  IL_000c: ldloc.0
  IL_000d: ret
 } // end of method '<>c__DisplayClass0_0'::'<Main>b__0'
} // end of class <>c__DisplayClass0_0二:循環(huán)下閉包玩法
為了方便說明,還是先上一段代碼。
static void Main(string[] args)
        {
            var actions = new Action[10];
            for (int i = 0; i < actions.Length; i++)
            {
                actions[i] = () => Console.WriteLine(i);
            }
            foreach (var item in actions) item();
        }然后把代碼跑起來:

我相信有非常多的朋友都踩過這個(gè)坑,那為什么會出現(xiàn)這樣的結(jié)果呢?我試著從原理上解讀一下。
1. 原理解讀
根據(jù)前面所學(xué)的 面向?qū)ο?nbsp;改造法,我相信大家肯定會很快改造出來,參考代碼如下:
class Program
    {
        static void Main(string[] args)
        {
            var actions = new Action[10];
            for (int i = 0; i < actions.Length; i++)
            {
                //actions[i] = () => Console.WriteLine(i);
                //改造后
                var funcClass = new FuncClass() { i = i };
                actions[i] = funcClass.Run;
            }
            foreach (var item in actions) item();
        }
    }
    public class FuncClass
    {
        public int i;
        public void Run()
        {
            Console.WriteLine(i);
        }
    }然后跑一下結(jié)果:

真奇葩,我們的改造方案一點(diǎn)問題都沒有,咋 編譯器 就弄不對呢?要想找到案例,只能看 MSIL 啦,簡化后如下:
IL_0001: ldc.i4.s 10
  IL_0003: newarr [System.Runtime]System.Action
  IL_0008: stloc.0
  IL_0009: newobj instance void ConsoleApp1.Program/'<>c__DisplayClass0_0'::.ctor()
  IL_000e: stloc.1
  IL_000f: ldloc.1
  IL_0010: ldc.i4.0
  IL_0011: stfld int32 ConsoleApp1.Program/'<>c__DisplayClass0_0'::i
  IL_0016: br.s IL_003e
  // loop start (head: IL_003e)
   IL_0018: nop
   IL_0019: ldloc.0
            ...
  // end loop如果有興趣大家可以看下完整版,它的實(shí)現(xiàn)方式大概是這樣的。
static void Main(string[] args)
        {
            var actions = new Action[10];
            var funcClass = new FuncClass();
            for (int i = 0; i < actions.Length; i++)
            {
                actions[i] = funcClass.Run;
                funcClass.i = i + 1;
            }
            foreach (var item in actions) item();
        }
原來問題就出在了它只 new 了一次,同時(shí) for 循環(huán)中只是對 i 進(jìn)行了賦值,導(dǎo)致了問題的發(fā)生。
2. 編譯器的想法
為什么編譯器會這么改造代碼,我覺得可能基于下面兩點(diǎn)。
- 不想 new 太多的類實(shí)例
 
new一個(gè)對象,其實(shí)并沒有大家想象的那么簡單,在 clr 內(nèi)部會分 快速路徑 和 慢速路徑,同時(shí)還為此導(dǎo)致 GC 回收,為了保存一個(gè)變量 需要專門 new 一個(gè)實(shí)例,這代價(jià)真的太大了。。。
- 有更好的解決辦法
 
更好的辦法就是用 方法參數(shù) ,方法的字節(jié)碼是放置在 CLR 的 codeheap 上,獨(dú)此一份,同時(shí)方法參數(shù)只是在棧上多了一個(gè)存儲空間而已,這代價(jià)就非常小了。
三:代碼改造
知道編譯器的苦衷后,改造起來就很簡單了,大概有如下兩種。
1. 強(qiáng)制 new 實(shí)例
這種改造法就是強(qiáng)制在每次 for 中 new 一個(gè)實(shí)例來承載 i 變量,參考代碼如下:
static void Main(string[] args)
        {
            var actions = new Action[10];
            for (int i = 0; i < actions.Length; i++)
            {
                var j = i;
                actions[i] = () => Console.WriteLine(j);
            }
            foreach (var item in actions) item();
        }
2. 采用方法參數(shù)
為了能夠讓 i 作為方法參數(shù),只能將 Action 改成 Action<int>,雖然你可能要為此掉頭發(fā),但對程序性能來說是巨大的,參考代碼如下:
static void Main(string[] args)
        {
            var actions = new Action<int>[10];
            for (int i = 0; i < actions.Length; i++)
            {
                actions[i] = (j) => Console.WriteLine(j);
            }
            for (int i = 0; i < actions.Length; i++)
            {
                actions[i](i);
            }
        }
好了,洋洋灑灑寫了這么多,希望對大家有幫助。















 
 
 









 
 
 
 