问题描述
有人知道下面的代码在C#编译器的作用吗?
Does anyone know what C# compiler does under the hood with the following code?
dict = new Dictionary<int, string>()
{
{ 1, "value1" },
{ 2, "value2" }
}
目前尚不清楚它是否创建KeyValuePair实例并调用Add方法,或者做一些更优化的事情。你们中有人知道吗?
It is not clear to if it creates the KeyValuePair instances and call the Add method, or do something more optimized. Does anyone of you know it?
推荐答案
它将称为添加
以值作为参数的对象上的方法:
It'll call the Add
method on the object with the values as arguments:
var __temp = new Dictionary<int, string>();
__temp.Add(1, "value1");
__temp.Add(2, "value2");
dict = __temp;
名称 Add
是硬编码的(在C#规范: 7.5.10.3 :集合初始化程序)。该方法的参数数量不受限制。它只需要匹配方法的参数数量。任何提供 Add
方法的集合(实现 IEnumerable
接口)都可以那样使用。
The name Add
is hardcoded (specified in the C# spec: 7.5.10.3: Collection initializers). The number of arguments to the method is not limited. It just has to match the number of parameters of the method. Any collection (implementing IEnumerable
interface) that provides an Add
method can be used like that.
为进一步澄清,不,编译器并不真正在意该类是 Dictionary
来创建 KeyValuePair
并将其传递给 Add
。它只是生成对 Add
方法的调用序列,并在每次调用中传递每个集合项中的所有参数。其余的由 Add
方法负责。
To further clarify, no, the compiler doesn't really care that the class is a Dictionary
to create a KeyValuePair
and pass that to Add
. It simply generates a sequence of calls to the Add
method passing all the arguments in each collection item in each call. The Add
method is responsible for the rest.
这篇关于使用数组初始化语法在C#上初始化Dictionary实例时,幕后发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!