装箱和拆箱,为什么输出都不都是"System.Object"? [英] boxing and unboxing, why aren't the outputs both "System.Object"?

查看:56
本文介绍了装箱和拆箱,为什么输出都不都是"System.Object"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下代码:

object var3 = 3;
Console.WriteLine(var3.GetType().ToString());
Console.WriteLine(typeof(object).ToString());

输出为:

System.Int32
System.Object

为什么都不都是 System.Object ?

推荐答案

如果您要问为什么boxedObject.GetType()不返回Object./strong>上的"MSDN装箱和拆箱"页面.好的问题顺便说一句..至少我对您的问题的理解.

If you're asking why the boxedObject.GetType() does not return Object.. check out the image under the Section 'Boxing Conversion' on the MSDN Boxing and Unboxing page. Good question btw.. atleast my understanding of your question.

尽管从技术上讲我可能不是正确的,但看起来像是

Although I may not be technically correct, it looks like

  • 移动到堆时,将创建一个新对象-其Type指针设置为原始值类型的Type对象(此处为System.Int32).这说明了GetType()(如果尝试将其拆箱为其他类型,还会显示该错误).
  • 然后将实际值复制到该对象中.
  • When moved to the heap, a new object is created - its Type pointer set to the original value type's Type object (here System.Int32). This explains GetType() (and also the error if you try to unbox it to a different type).
  • The actual value is then copied over into this object.

这篇关于装箱和拆箱,为什么输出都不都是"System.Object"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆