在字典初始值设定项中,有两种方法可以使用内容创建字典: new Dictionarystring, GradientSpace{ ["userSpaceOnUse"] = GradientSpace.Absolute, ["objectBoundingBox"] = GradientSpace.Relative}) 和 new Dictionarystring, Gra
new Dictionary<string, GradientSpace> { ["userSpaceOnUse"] = GradientSpace.Absolute, ["objectBoundingBox"] = GradientSpace.Relative })
和
new Dictionary<string, GradientSpace> { {"userSpaceOnUse", GradientSpace.Absolute}, {"objectBoundingBox", GradientSpace.Relative} });
在这两种语法中是否存在任何差异,或者仅仅是偏好问题?
当源代码如下并且目标框架是.NET 4.7.1时:var x = new Dictionary<string, int> { ["userSpaceOnUse"] = 1, ["objectBoundingBox"] = 3 }; var y = new Dictionary<string, int> { {"userSpaceOnUse", 1}, {"objectBoundingBox", 3} };
这导致以下中间语言(使用JetBrains dotPeek):
// [18 13 - 22 15] IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::.ctor() IL_0006: dup IL_0007: ldstr "userSpaceOnUse" IL_000c: ldc.i4.1 IL_000d: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::set_Item(!0/*string*/, !1/*int32*/) IL_0012: nop IL_0013: dup IL_0014: ldstr "objectBoundingBox" IL_0019: ldc.i4.3 IL_001a: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::set_Item(!0/*string*/, !1/*int32*/) IL_001f: nop IL_0020: stloc.0 // x // [25 13 - 28 15] IL_0021: newobj instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::.ctor() IL_0026: dup IL_0027: ldstr "userSpaceOnUse" IL_002c: ldc.i4.1 IL_002d: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0/*string*/, !1/*int32*/) IL_0032: nop IL_0033: dup IL_0034: ldstr "objectBoundingBox" IL_0039: ldc.i4.3 IL_003a: callvirt instance void class [mscorlib]System.Collections.Generic.Dictionary`2<string, int32>::Add(!0/*string*/, !1/*int32*/) IL_003f: nop IL_0040: stloc.1 // y
第一种方法导致设置索引器/属性,而第二种方式使用Add()方法,这意味着它们的翻译方式不同.
在这种情况下,Dictionarry类的.NET Core源也很有趣:
https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/collections/generic/dictionary.cs