C# 中編譯器是如何?閉包的

來源:互聯網
上載者:User

 首先假設我們有如下的一個擴充方法:      

        public static void LockExec<T>(this T obj, Action<T> action) where T : class
{
lock (obj)
{
action(obj);
}
}

我們用這個擴充方法寫下了如下的代碼:

        static void TestInsert(bool canInsert, string insertValue)
{
var list1 = new List<string>();
list1.LockExec(
(list) =>
{
if (canInsert && !list.Contains(insertValue))
{
list.Add(insertValue);
}
});
}

在這個例子中的Lambda運算式中從表面看來只有list是Action<T>傳進來的變數,canInsert,insertValue對於Lamba運算式來時都是外部變數,為什麼這個運算式還能通過編譯且正確運行呢?其實這是c#編譯器幫我們做的一個工作,c#編譯器將上面的代碼編譯成下邊的代碼,編譯器為我們產生了一個內部類,來儲存Lambda運算式引用的外部變數值,並將這個內部類的執行個體方法傳遞給Action<T>,這樣這個Action<T>對象的Target和Mothed屬性就都有值了,而且這個Action<T>的方法調用將採用執行個體方法調用,也就是說會有this指標。

    static void TestInsert(bool canInsert, string insertValue)
{
var list1 = new List<string>();
var innerClass = new InnerClass { InnerProperty1 = canInsert, InnerProperty2 = insertValue };
list1.LockExec(innerClass.InnerMothed);
}

internal class InnerClass
{
public bool InnerProperty1
{
get; set;
}

public string InnerProperty2
{
get; set;
}

public void InnerMothed(List<string> list)
{
if (InnerProperty1 && !list.Contains(InnerProperty2))
{
list.Add(InnerProperty2);
}
}
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.