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},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,!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,!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
以上是内存溢出为你收集整理的c# – 在字典初始值设定项中使用方括号和花括号之间有区别吗?全部内容,希望文章能够帮你解决c# – 在字典初始值设定项中使用方括号和花括号之间有区别吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)