5
var i = new int[2];

Is "i" considered to be boxed?

4

4 回答 4

9

No there is nothing to box. The var keyword doesn't mean that the variable is boxxed. It doesn't do any conversion during the runtime. The var keyword is strictly a C# construct. What is actually happening when you use var is:

var i = new int[1];

IL sees it as:

int[] i = new int[1]

Now if you are asking if when you assign an int to part of the array of i does it box?

such as:

i[0] = 2;

No it does not.

This is opposed to which does:

var o = new object[1];

o[0] = 2;

This example does and why using ArrayList (think expandable array) in 1.0, 1.1 (pre generics) was a huge cost. The following comment applies to the object[] example as well:

Any reference or value type that is added to an ArrayList is implicitly upcast to Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. Both the casting and the boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate over large collections.

MSDN Link to ArrayList

Link to Boxing in C#

于 2010-06-05T13:08:56.900 回答
7

Assuming this is C# (var and C#-like array syntax), no, i is not boxed. Only primitive value types (think numeric values) can be boxed.

The values in the array are not boxed either, since values in primitive arrays do not get boxed.

于 2010-06-05T13:03:56.063 回答
4

Array in C# is referential type so there's no need for boxing. You will however have boxing in this example:

var i = 123;
object o = i;
于 2010-06-05T13:03:47.950 回答
3

装箱仅在值类型(即原始类型、结构或枚举)被视为引用类型时发生。您的数组被声明为保存 type 的值int。该var关键字仅告诉编译器推断变量的类型i,而不是您手动指定它。

你是否写过:

var i = new object[2];

编译器会将其转换为object[] i = new object[2],并且您输入的任何int值都会被装箱。您放在同一个数组中的任何引用类型都不需要任何装箱。

总之,var与拳击无关。

这是.NET中不同类型的图表。您可能还想阅读.NET 类型基础知识

于 2010-06-05T13:27:03.413 回答