在ArrayList中“存储”值类型

时间:2011-12-01 13:06:21

标签: c# .net 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?

4 个答案:

答案 0 :(得分:12)

它被称为“拳击”:自动将int转换为引用类型。这确实会带来一些性能。

另见Boxing and Unboxing

答案 1 :(得分:2)

如果您在ILSpy中提取ArrayList类,您将看到后备存储是:

private object[] _items;

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

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

因此,当您使用整数,Add整数调用_items时,它会被ArrayList中的object数组添加为ArrayList }}

顺便提一下,如果你需要int只是整数并且你正在使用.NET 2.0 Framework或更高版本,那么你应该使用boxes(也就是通用List)类,这样做会更好因为它避免了在列表中存储或检索它时必须打{{1}}(参见最后一个链接中的性能注意事项部分)。

答案 2 :(得分:1)

它叫拳击。 “Box”包含结构的副本以及它的类型的详细信息。

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

在框架2.0中,microsoft为我们提供了更快,更有效的泛型:

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

答案 3 :(得分:0)

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

相关问题