介紹C# Anonymous Type
C# Anonymous Type僅僅是C# 3.0的新的特性,而沒有說Anonymous Type是.NET Framework 3.5的新特性。這是因為Anonymous Type僅僅是.NET Programming Language和相應(yīng)的Compiler的新引入的特征。而對于.NET Framework 3.5來說,它看不到這和原來有什么不同,換句話說,對于Anonymous Type和一般的Named Type,對于CLR來說他們之間沒有什么本質(zhì)的區(qū)別。
對于下面這樣的一段簡單的代碼:
- public sealed class <>f__AnonymousType0<<>j__AnonymousTypeTypeParameter1,
<>j__AnonymousTypeTypeParameter2>- {
- // Properties
- public <>j__AnonymousTypeTypeParameter1ID{ get; set; }
- public j__AnonymousTypeTypeParameter2 Name{ get; set; }
- // Fields
- private j__AnonymousTypeTypeParameter1 <>i__AnonymousTypeField3;
- private j__AnonymousTypeTypeParameter2 <>i__AnonymousTypeField4;
- }
< >j__Anonymous Type Type Parameter1 和< >j__Anonymous Type Type Parameter2這兩個Generic Type代表我在 {} 中制定ID和Name的類型。通過這個結(jié)構(gòu),我們發(fā)現(xiàn)其定義和一般的Generic Type并沒有什么區(qū)別。
為了進一步了解生成什么樣的C# Anonymous Type,我們使用IL DASM在IL級別看看生成的Anonymous Type的大體結(jié)構(gòu):
為了做一個對比,下面是我們最開始定義的Named Employee Type在IL DASM中的結(jié)構(gòu):
如果想更清楚了解C# Anonymous Type的本質(zhì),建議讀者親自使用IL DASM看看的每個成員具體的IL。
【編輯推薦】