문제

I believe the C# compiler will rewrite foreach into a for when it is used on ordinary arrays (such as int[]). However, for collections that store a struct, will boxing result from iterating its contents?

For example, does the code below rely on boxing (IEnumerable<KeyValuePair<int,byte>>) to iterate the contents of dict?

void DoSomething(Dictionary<int,byte> dict) {
    foreach(KeyValuePair<int,byte> itr in dict)
        m_correlation += itr.Key; }
도움이 되었습니까?

해결책

No, the above code does no boxing.

If you'd used IDictionary<int, byte> as the argument (or IEnumerable<KeyValuePair<int, byte>>), the enumerator itself would get boxed, since the dictionary class, like many collections, have a struct enumerator (to save an object allocation every time you call foreach).

In the code above, the compiler would call the dictionary's GetEnumerator method, rather than the (implicitly implemented) IEnumerable<T> method.

다른 팁

No it won't.

Nothing from the above can be boxed. Your Dictionary is already a reference type.. and a KeyValuePair is a struct. The compiler generated call to GetEnumerator() will return a generic Enumerator struct.. but that is called on dict.. which is already a reference type.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top