装箱和取消装箱(C# 编程指南)Boxing and Unboxing (C# Programming Guide)

装箱是将值类型转换为 object 类型或由此值类型实现的任何接口类型的过程。Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. CLR 对值类型进行装箱时,会将值包装在 System.Object 实例中并将其存储在托管堆中。When the CLR boxes a value type, it wraps the value inside a System.Object instance and stores it on the managed heap. 取消装箱将从对象中提取值类型。Unboxing extracts the value type from the object. 装箱是隐式的;取消装箱是显式的。Boxing is implicit; unboxing is explicit. 装箱和取消装箱的概念是类型系统 C# 统一视图的基础,其中任一类型的值都被视为一个对象。The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

下例将整型变量 i 进行了装箱 并分配给对象 oIn the following example, the integer variable i is boxed and assigned to object o.

int i = 123;
// The following line boxes i.
object o = i;  

然后,可以将对象 o 取消装箱并分配给整型变量 iThe object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;  // unboxing

以下示例演示如何在 C# 中使用装箱。The following examples illustrate how boxing is used in C#.

// String.Concat example.
// String.Concat has many versions. Rest the mouse pointer on 
// Concat in the following statement to verify that the version
// that is used here takes three object arguments. Both 42 and
// true must be boxed.
Console.WriteLine(String.Concat("Answer", 42, true));


// List example.
// Create a list of objects to hold a heterogeneous collection 
// of elements.
List<object> mixedList = new List<object>();

// Add a string element to the list. 
mixedList.Add("First Group:");

// Add some integers to the list. 
for (int j = 1; j < 5; j++)
{
    // Rest the mouse pointer over j to verify that you are adding
    // an int to a list of objects. Each element j is boxed when 
    // you add j to mixedList.
    mixedList.Add(j);
}

// Add another string and more integers.
mixedList.Add("Second Group:");
for (int j = 5; j < 10; j++)
{
    mixedList.Add(j);
}

// Display the elements in the list. Declare the loop variable by 
// using var, so that the compiler assigns its type.
foreach (var item in mixedList)
{
    // Rest the mouse pointer over item to verify that the elements
    // of mixedList are objects.
    Console.WriteLine(item);
}

// The following loop sums the squares of the first group of boxed
// integers in mixedList. The list elements are objects, and cannot
// be multiplied or added to the sum until they are unboxed. The
// unboxing must be done explicitly.
var sum = 0;
for (var j = 1; j < 5; j++)
{
    // The following statement causes a compiler error: Operator 
    // '*' cannot be applied to operands of type 'object' and
    // 'object'. 
    //sum += mixedList[j] * mixedList[j]);

    // After the list elements are unboxed, the computation does 
    // not cause a compiler error.
    sum += (int)mixedList[j] * (int)mixedList[j];
}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.
Console.WriteLine("Sum: " + sum);

// Output:
// Answer42True
// First Group:
// 1
// 2
// 3
// 4
// Second Group:
// 5
// 6
// 7
// 8
// 9
// Sum: 30

性能Performance

相对于简单的赋值而言,装箱和取消装箱过程需要进行大量的计算。In relation to simple assignments, boxing and unboxing are computationally expensive processes. 对值类型进行装箱时,必须分配并构造一个新对象。When a value type is boxed, a new object must be allocated and constructed. 取消装箱所需的强制转换也需要进行大量的计算,只是程度较轻。To a lesser degree, the cast required for unboxing is also expensive computationally. 有关更多信息,请参阅性能For more information, see Performance.

装箱Boxing

装箱用于在垃圾回收堆中存储值类型。Boxing is used to store value types in the garbage-collected heap. 装箱是值类型object 类型或到此值类型所实现的任何接口类型的隐式转换。Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. 对值类型装箱会在堆中分配一个对象实例,并将该值复制到新的对象中。Boxing a value type allocates an object instance on the heap and copies the value into the new object.

请看以下值类型变量的声明:Consider the following declaration of a value-type variable:

int i = 123;

以下语句对变量 i 隐式应用了装箱操作:The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o.
object o = i;  

此语句的结果是在堆栈上创建对象引用 o,而在堆上则引用 int 类型的值。The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. 该值是赋给变量 i 的值类型值的一个副本。This value is a copy of the value-type value assigned to the variable i. 以下装箱转换图说明了 io 这两个变量之间的差异:The difference between the two variables, i and o, is illustrated in the following image of boxing conversion:

显示 i 和 o 变量之间的差异的图。

还可以像下面的示例一样执行显式装箱,但显式装箱从来不是必需的:It is also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:

int i = 123;
object o = (object)i;  // explicit boxing

说明Description

此示例使用装箱将整型变量 i 转换为对象 oThis example converts an integer variable i to an object o by using boxing. 这样一来,存储在变量 i 中的值就从 123 更改为 456Then, the value stored in the variable i is changed from 123 to 456. 该示例表明原始值类型和装箱的对象使用不同的内存位置,因此能够存储不同的值。The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.

示例Example

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o.
        object o = i;  

        // Change the value of i.
        i = 456;  

        // The change in i doesn't affect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

取消装箱Unboxing

取消装箱是从 object 类型到值类型或从接口类型到实现该接口的值类型的显式转换。Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. 取消装箱操作包括:An unboxing operation consists of:

  • 检查对象实例,以确保它是给定值类型的装箱值。Checking the object instance to make sure that it is a boxed value of the given value type.

  • 将该值从实例复制到值类型变量中。Copying the value from the instance into the value-type variable.

下面的语句演示装箱和取消装箱两种操作:The following statements demonstrate both boxing and unboxing operations:

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

下图演示了上述语句的结果:The following figure demonstrates the result of the previous statements:

显示取消装箱转换的图。

要在运行时成功取消装箱值类型,被取消装箱的项必须是对一个对象的引用,该对象是先前通过装箱该值类型的实例创建的。For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. 尝试取消装箱 null 会导致 NullReferenceExceptionAttempting to unbox null causes a NullReferenceException. 尝试取消装箱对不兼容值类型的引用会导致 InvalidCastExceptionAttempting to unbox a reference to an incompatible value type causes an InvalidCastException.

示例Example

下面的示例演示无效的取消装箱及引发的 InvalidCastExceptionThe following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. 使用 trycatch,在发生错误时显示错误信息。Using try and catch, an error message is displayed when the error occurs.

class TestUnboxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        try
        {
            int j = (short)o;  // attempt to unbox

            System.Console.WriteLine("Unboxing OK.");
        }
        catch (System.InvalidCastException e)
        {
            System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
        }
    }
}

此程序输出:This program outputs:

Specified cast is not valid. Error: Incorrect unboxing.

如果将下列语句:If you change the statement:

int j = (short) o;  

更改为:to:

int j = (int) o;  

将执行转换,并将得到以下输出:the conversion will be performed, and you will get the output:

Unboxing OK.

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

更多相关信息:For more information:

请参阅See also