2011-12-01 74 views
7

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? 
+0

的可能重複[如何在.NET 「拳擊」 的工作? ](http://stackoverflow.com/questions/5997398/how-does-boxing-work-in-net) –

+5

不是真的 - 如果你已經知道這個問題的答案,你只會知道這兩者是相關的。 – mavnn

+1

@Binary worrier - 這是相同的主題,但那麼你需要知道它是怎麼叫的.. –

回答

12

它被稱爲「裝箱」:automagically int被轉換爲引用類型。這確實會花費一些性能。請參閱Boxing and Unboxing

0

Arraylist.Add()將添加任何值並添加爲對象,因此整數值將自動轉換(裝箱)並添加到arraylist中。

2

如果你拉在ILSpy的ArrayList類,你會看到,後備存儲是:

private object[] _items; 

,而且Add方法接受object類型的實例:

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

所以當你用一個整數調用Add,.NET boxes這個整數,然後它被作爲object添加到的_items數組中。順便說一句,如果你需要一個整數的ArrayList,並且你使用的是.NET 2.0框架或更高版本,你應該使用List<T>(又名泛型列表)類,它會更好地執行,因爲它避免了必須裝箱int從列表中存儲或檢索時(請參閱最後一個鏈接中的性能注意事項部分)。