也就是e1的对象载入简化了。看代码大小也能发现新写法的优势。
对应的就是集合初始化
c# 2.0
c# 3.0List<Employee> list1 = new List<Employee>(); list1.Add(e1);
对应的ILList<Employee> list2 = new List<Employee> { new Employee(3) { Age = 25, Name = "james" }, new Employee(4) { Age = 26, Name = "tony" } };
c#2.0
c#3.0.method public hidebysig instance void dd() cil managed { // 代码大小 21 (0x15) .maxstack 2 .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee> list1) IL_0000: nop IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee>::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldarg.0 IL_0009: ldfld class WindowsFormsApplication1.Employee WindowsFormsApplication1.TestInitializer::e1 IL_000e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee>::Add(!0) IL_0013: nop IL_0014: ret } // end of method TestInitializer::dd
两个的init是不同的,至于为什么3.0里会由编译器init出来第二个参数我还不大明白,还请各位看客指点。.method public hidebysig instance void newdd() cil managed { // 代码大小 23 (0x17) .maxstack 2 .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee> list2, [1] class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee> '<>g__initLocal1') IL_0000: nop IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee>::.ctor() IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldarg.0 IL_0009: ldfld class WindowsFormsApplication1.Employee WindowsFormsApplication1.TestInitializer::e1 IL_000e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<class WindowsFormsApplication1.Employee>::Add(!0) IL_0013: nop IL_0014: ldloc.1 IL_0015: stloc.0 IL_0016: ret } // end of method TestInitializer::newdd
看到这里大家也该明白如何写代码才是最好的了吧。