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

Mr.*_*ith 3 c# optimization boxing

相信C#编译器在普通数组(如.)上使用时会改写foreach成a 。但是,对于存储 a 的集合,会因迭代其内容而导致装箱吗?forint[]struct

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

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

Eli*_*bel 5

不,上面的代码没有装箱。

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

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