简体   繁体   中英

When using object type stores an int value, why the object.GetType() returns system.Int32?

The code like below:

object i = 11;

Console.WriteLine(i.GetType());

It prints out "System.Int32", why? I thought it should be "system.object".

GetType() returns the actual type of the object that the value refers to. It doesn't return the type of the variable used to access the object. So as a simpler example:

object x = "this is a string";
Console.WriteLine(x.GetType()); // Prints System.String

In this case, the type is "boxed System.Int32 " - but most of .NET doesn't differentiate between "a regular value type" and "the boxed type equivalent to the value type", including GetType() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM