foreach是否在IEnumerable <struct>?</struct>上应用装箱

时间:2013-09-16 04:58:26

标签: c# optimization boxing

我相信当C#编译器在普通数组(例如foreach)上使用时,会将for重写为int[]。但是,对于存储struct的集合,是否会通过迭代其内容来装箱?

例如,下面的代码是否依赖装箱(IEnumerable<KeyValuePair<int,byte>>)来迭代dict的内容?

void DoSomething(Dictionary<int,byte> dict) {
    foreach(KeyValuePair<int,byte> itr in dict)
        m_correlation += itr.Key; }

2 个答案:

答案 0 :(得分:3)

不,上面的代码没有拳击。

如果您使用IDictionary<int, byte>作为参数(或IEnumerable<KeyValuePair<int, byte>>),则枚举器本身会被装箱,因为字典类与许多集合一样,具有struct枚举器(每次调用foreach时保存对象分配)。

在上面的代码中,编译器会调用字典的GetEnumerator方法,而不是(隐式实现的)IEnumerable<T>方法。

答案 1 :(得分:1)

不,不会。

上述中的任何内容都不能装箱。您的Dictionary已经是参考类型.. KeyValuePairstruct。编译器生成的对GetEnumerator()的调用将返回一个通用的枚举器struct ..但是在dict上调用..它已经是一个引用类型。