在ArrayList中"存储"值类型

Bir*_*man 7 .net c# arraylist

ArrayList级只能包含对象的引用,但是当你存储的值类型会发生什么,如整数?

string str = "Hello";
int i = 50;

ArrayList arraylist = new ArrayList();

arraylist.Add(str); // Makes perfectly sense: 
                    // Reference to string-object (instance) "Hello" is added to 
                    // index number 0

arraylist.Add(i);   // What happens here? How can a reference point to a value 
                    // type? Is the value type automatically converted to an 
                    // object and thereafter added to the ArrayList?
Run Code Online (Sandbox Code Playgroud)

Han*_*ing 12

它被称为"装箱":自动将int转换为引用类型.这确实需要一些性能.

另见拳击和拆箱.