概述:
在初始化的时候根据初始化列表自动产生类型的一种机制。
实例代码:
运行结果:
2
4
this is a string
在初始化的时候根据初始化列表自动产生类型的一种机制。
实例代码:
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);
}
{
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 ([0] class '<>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
由此可见,在编译的时候确实已经已经根据列表中的值确定了其类型。{
.entrypoint
// Code size 51 (0x33)
.maxstack 4
.locals init ([0] class '<>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