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视图就知道了。
C#3.0 为我们带来什么(5) —— 匿名类型

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

相关文章:

  • 2021-05-31
  • 2021-11-25
  • 2021-12-03
  • 2021-12-31
  • 2021-09-26
  • 2021-07-20
  • 2022-12-23
猜你喜欢
  • 2021-09-26
  • 2022-03-06
  • 2021-06-29
  • 2021-08-20
  • 2021-09-19
  • 2021-08-29
相关资源
相似解决方案