C#3.0 为我们带来什么(5) —— 匿名类型

文/tianyamoon  出处/博客园

var employee= new{Age =25,Name = "james" }
无须显示声明一个类,而且在初始化器里面可以获取上下文的变量——闭包
这就是C#3.0里提供的匿名类型。
并且可以对声明的类型进行这样的访问
string name = employee.name;

来看看IL的实现。
.method public hidebysig instance void  dd() cil managed
{
  // 代码大小      22 (0x16)
  .maxstack  3
  .locals init ([0] class '<>f__AnonymousType0`2'<int32,string> employee,
          [1] string name)
  IL_0000:  nop
  IL_0001:  ldc.i4.s  25
  IL_0003:  ldstr      "james"
  IL_0008:  newobj    instance void class '<>f__AnonymousType0`2'<int32,string>::.ctor(!0,
                                                                                        !1)
  IL_000d:  stloc.0
  IL_000e:  ldloc.0
  IL_000f:  callvirt  instance !1 class '<>f__AnonymousType0`2'<int32,string>::get_Name()
  IL_0014:  stloc.1
  IL_0015:  ret
} // end of method testvar::dd
看到代码会想'<>f__AnonymousType0`2'从何而来呢?
来看il视图就知道了。

 附件: 您所在的用户组无法下载或查看附件

虽然匿名类型非常方便,但是我们无法通过代码来访问到'<>f__AnonymousType0`2',而且var不能定义全局变量与参数类型,所以导致了我们创建的匿名类型实例只能应用在函数内部。从而限制了匿名类型的使用。

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [C#] 的这些文章也感兴趣:

在IE中托管WindowsForm
C#制作动画效果
如何调试你的C#程序(2)
简易C#的IDE
winform 未能找到任何适合于指定的区域性或非特定区域性的资源
C#进阶(八)
利用VisualC#实现Window管道技术
用设计模式固化你的C#程序(尾篇一)
利用Mutex实现应用程序的单实例运行
C#积木模块ABC(一)