“Storing"数组列表中的值类型

本文关键字:类型 列表 数组 Storing quot | 更新日期: 2023-09-27 18:16:15

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?

“Storing"数组列表中的值类型

这被称为"装箱":int自动转换为引用类型。

参见装箱和拆箱。

如果您在ILSpy中打开ArrayList类,您将看到后备存储为:

private object[] _items;

并且Add方法接受类型为object的实例:

public virtual int Add(object value) { ... }

所以当你用一个整数调用Add时,. net将这个整数框起来,然后将它作为object添加到ArrayList中的_items数组中。

顺便说一下,如果你只需要一个整数的ArrayList,并且你正在使用。net 2.0框架或更高版本,你应该使用List<(又名泛型列表)类,它将执行得更好,因为它避免了在存储或从列表中检索int时必须将其装箱(请参阅最后一个链接中的性能考虑部分)。

这叫做装箱。"Box"保存着该结构体的副本以及该结构体类型的详细信息。

MSDN: http://msdn.microsoft.com/en-us/library/yz2be5wk%28v=vs.80%29.aspx

在framework 2.0 +中,microsoft给了我们更快更有效的泛型:

MSDN: http://msdn.microsoft.com/en-us/library/ms172192.aspx

arraylist. add()将添加任何值并将其添加为对象,因此整数值将自动转换(装箱)并添加到arraylist中。