在 C# 中从列表到对象的装箱和拆箱

Boxing and UnBoxing from List to Object in C#

我想知道我的做法是对还是错?

参考两个语句

案例:#1

List<string> person = new List<string>() {
                            "Harry"
                            "Emma"
                            "Watson"
                        }

案例:#2

Object person = new List<string>() {
                            "Harry"
                            "Emma"
                            "Watson"
                        }

告诉我

哪个语句是 装箱 哪个语句是 拆箱 ?

两个陈述相等且相同 ???

None 个。 装箱和拆箱是.NET中统一类型系统提供的一种处理值类型的机制。

例如:

int i = 4;
object o = i; //boxing, int is boxed in an object
int j = (int)o; //unboxing, an int is unboxed from an object

来自 MSDN:

详细了解 why we need boxing and unboxing

可空类型的装箱有一个特例。 当一个可为空的类型装箱时,它装箱为其值或空值。您不能将可为 null 的值装箱。

int? a = 4;
object o = a; //boxing, o is a boxed int now
Console.WriteLine(o.GetType()); //System.Int32
int? b = null;
o = b; //boxing, o is null
Console.WriteLine(o.GetType()); // NullReferenceException

没有装箱,因为 List 是引用类型:

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type

Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. 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.

阅读更多:MSDN

这是拳击:

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

这是开箱:

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

这不是装箱或拆箱。

装箱就是把value type存入the reference type,拆箱就是boxing的逆向。

在你的例子中,List 和 Object 都是 reference type。你只是在玩引用

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

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

int -> object boxing

object -> int unboxing

更多信息请看这里Boxing and Unboxing