c# 装箱和拆箱
简单一句话:将值类型的变量转换为对象的过程称为“装箱”。将对象类型的变量转换为值类型的过程称为“拆箱”。
更多详解参见:.net中6个重要的基础概念:Stack, heap, Value types, reference types, boxing and Unboxing.
创建控制台程序:BoxingAndUnboxing.cs
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSType
{
public class BoxingAndUnboxing
{
public BoxingAndUnboxing()
{
int i = 123;
object o = (object)i; // boxing
Console.WriteLine("Type o:"+o.GetType());
//output System.Int32
o = 123;
i = (int)o; // unboxing
Console.WriteLine(i.GetType());
//output System.Int32
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSType
{
public class BoxingAndUnboxing
{
public BoxingAndUnboxing()
{
int i = 123;
object o = (object)i; // boxing
Console.WriteLine("Type o:"+o.GetType());
//output System.Int32
o = 123;
i = (int)o; // unboxing
Console.WriteLine(i.GetType());
//output System.Int32
Console.ReadLine();
}
}
}