介绍C# Anonymous Type

C# Anonymous Type仅仅是C# 3.0的新的特性,而没有说Anonymous Type是.NET Framework 3.5的新特性。这是因为Anonymous Type仅仅是.NET Programming Language和相应的Compiler的新引入的特征。而对于.NET Framework 3.5来说,它看不到这和原来有什么不同,换句话说,对于Anonymous Type和一般的Named Type,对于CLR来说他们之间没有什么本质的区别。

对于下面这样的一段简单的代码:

 
 
 
 
  1. public sealed class <>f__AnonymousType0<<>j__AnonymousTypeTypeParameter1, 
    <>j__AnonymousTypeTypeParameter2> 
  2. {  
  3. // Properties  
  4. public <>j__AnonymousTypeTypeParameter1ID{ get; set; }  
  5. public j__AnonymousTypeTypeParameter2 Name{ get; set; }  
  6. // Fields  
  7. private j__AnonymousTypeTypeParameter1 <>i__AnonymousTypeField3;  
  8. private j__AnonymousTypeTypeParameter2 <>i__AnonymousTypeField4;  

< >j__Anonymous Type Type Parameter1 和< >j__Anonymous Type Type Parameter2这两个Generic Type代表我在 {} 中制定ID和Name的类型。通过这个结构,我们发现其定义和一般的Generic Type并没有什么区别。

为了进一步了解生成什么样的C# Anonymous Type,我们使用IL DASM在IL级别看看生成的Anonymous Type的大体结构:

为了做一个对比,下面是我们最开始定义的Named Employee Type在IL DASM中的结构:

 

如果想更清楚了解C# Anonymous Type的本质,建议读者亲自使用IL DASM看看的每个成员具体的IL。

【编辑推荐】

  1. 浅析C# ArrayList
  2. C#对象初始化学习总结
  3. 使用C#正则表达式匹配相关字符串
  4. C#改写方法学习笔记
  5. 概述C#加框和消框
THE END