Collections and Generics

The Problems of Nongeneric Collections

非泛型集合的问题

The first issue is that using the System.Collections and System.Collections.Specialized classes can result in some poorly performing code, especially when you are manipulating numerical data (e.g., value types).

The second issue is that most of the nongeneric collection classes are not type safe because (again) they were developed to operate on System.Objects, and they could therefore contain anything at all.

The Issue of Performance

To do so, C# provides a simple mechanism, termed boxing, to store the data in a value type within a reference variable. Boxing can be formally defined as the process of explicitly assigning a value type to a System.Object variable.

为了做这个,C#提供了一个简单的机制,叫做装箱来使用一个引用型变量存储值类型的数据。装箱可以显示的把一个值类型赋给System.Object变量。

When you box a value, the CLR allocates a new object on the heap and copies the value type’s value (25, in this case) into that instance. What is returned to you is a reference to the newly allocated heap-based object.

Unboxing is the process of converting the value held in the object reference back into a corresponding value type on the stack. 

The CLR begins by verifying that the receiving data type is equivalent to the boxed type; and if so, it copies the value back into a local stack-based variable.

The Issue of Type Safety

posted @ 2015-02-04 16:19  海川0  阅读(70)  评论(0)    收藏  举报