c# – 在字典初始值设定项中使用方括号和花括号之间有区别吗?

c# – 在字典初始值设定项中使用方括号和花括号之间有区别吗?,第1张

概述在字典初始值设定项中,有两种方法可以使用内容创建字典: new Dictionary<string, GradientSpace>{ ["userSpaceOnUse"] = GradientSpace.Absolute, ["objectBoundingBox"] = GradientSpace.Relative}) 和 new Dictionary<string, Grad 在字典初始值设定项中,有两种方法可以使用内容创建字典:

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# – 在字典初始值设定项中使用方括号和花括号之间有区别吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1215058.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存