zoukankan      html  css  js  c++  java
  • 匿名类型(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
  • 相关阅读:
    Linux下C程序插入执行shell脚本
    #ifdef预编译相关用法
    LAMP开发之环境搭建(2014.12.7在ubuntu下)
    Qt在VS2010的安装与配置
    vs2010配备boost编程环境
    Ubuntu虚拟机与Window、Arm的通信
    大小端测试程序
    Ubuntu安装google Gtest
    设计模式之单例模式
    设计模式之原型模式
  • 原文地址:https://www.cnblogs.com/abcdwxc/p/966677.html
Copyright © 2011-2022 走看看