我对装箱和拆箱有点困惑。根据其定义
Boxing is implicit conversion of ValueTypes to Reference Types (Object).
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes.
描述这个的最好例子是
int i = 123; object o = i; // boxing
和
o = 123; i = (int)o; // unboxing
但是我的问题是int是值类型还是string是引用类型所以
int i = 123; string s = i.ToString();
和
s = "123"; i = (int)s;
这是装箱拆箱的例子吗???
最佳答案
调用 ToString
不是装箱。它创建一个新字符串,恰好包含您的 int 的文本表示。
当调用 (object)1
时,这会在堆上创建一个包含 int 的新实例。但它仍然是一个 int
。 (您可以使用 o.GetType()
进行验证)
String 无法转换为 int
。所以你的代码不会编译。
如果您首先将字符串转换为 object
,您的代码将编译但在运行时失败,因为您的对象不是装箱的 int。您只能将值类型拆箱为完全正确的类型(或关联的可空类型)。
两个例子:
损坏:
object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int
工作:
object o=i;// o is a boxed int
int i2=(int)o;//works
关于c# - 在 int 和 string 中装箱和拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423452/