boxing and unboxing, why aren't the outputs both “System.Object”?

前端 未结 5 1438
情书的邮戳
情书的邮戳 2021-02-15 15:45

I got the following code:

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

The outp

5条回答
  •  逝去的感伤
    2021-02-15 16:38

    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

    • 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.

提交回复
热议问题