匿名类型(Anonymouse Type)

概述:
    在初始化的时候根据初始化列表自动产生类型的一种机制。
实例代码:    
       public   static   void  Main()
            
{
              var x 
= new { a = 2, b = 4, c = "this is a string" };
               Console.WriteLine(x.a);  
                Console.WriteLine(x.b);
                Console.WriteLine(x.c);
          }

现在我们看一下,编译后的中间语言。

.method  public  hidebysig  static   void   Main() cil managed
{
  .entrypoint
  
// Code size       51 (0x33)
  .maxstack  4
  .locals init ([
0class '<>f__AnonymousType0`3'<int32,int32,string> x)
  IL_0000:  nop
  IL_0001:  ldc.i4.
2
  IL_0002:  ldc.i4.
4
  IL_0003:  ldstr      
"this is a string"
  IL_0008:  newobj     instance 
void class '<>f__AnonymousType0`3'<int32,int32,string>::.ctor(!0,
                                                                                              
!1,
                                                                                              
!2)
  IL_000d:  stloc.
0
  IL_000e:  ldloc.
0
  IL_000f:  callvirt   instance 
!0 class '<>f__AnonymousType0`3'<int32,int32,string>::get_a()
  IL_0014:  call       
void [mscorlib]System.Console::WriteLine(int32)
  IL_0019:  nop
  IL_001a:  ldloc.
0
  IL_001b:  callvirt   instance 
!1 class '<>f__AnonymousType0`3'<int32,int32,string>::get_b()
  IL_0020:  call       
void [mscorlib]System.Console::WriteLine(int32)
  IL_0025:  nop
  IL_0026:  ldloc.
0
  IL_0027:  callvirt   instance 
!2 class '<>f__AnonymousType0`3'<int32,int32,string>::get_c()
  IL_002c:  call       
void [mscorlib]System.Console::WriteLine(string)
  IL_0031:  nop
  IL_0032:  ret
}
  //  end of method NewTest::Main
由此可见,在编译的时候确实已经已经根据列表中的值确定了其类型。
运行结果:
2
4
this is a string
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值