简体   繁体   English

当使用 object 类型存储一个 int 值时,为什么 object.GetType() 返回 system.Int32?

[英]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?它打印出“System.Int32”,为什么? I thought it should be "system.object".我认为它应该是“system.object”。

GetType() returns the actual type of the object that the value refers to. GetType()返回该值所指的 object 的实际类型 It doesn't return the type of the variable used to access the object.它不返回用于访问 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() .在这种情况下,类型是“boxed System.Int32 ” - 但 .NET 的大部分内容都没有区分“常规值类型”和“与值类型等效的盒装类型”,包括GetType()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用LINQ删除重复项将返回“错误:删除重复项:无法将类型为'System.Int32'的对象转换为类型为'System.String'。” - Removing duplicates using LINQ returns “Error removing duplicates: Unable to cast object of type 'System.Int32' to type 'System.String'.” 错误“无法将'System.Int32'类型的对象强制转换为'System.Collections.Generic.List`1 [System.Int32]'' - error “Unable to cast object of type 'System.Int32' to type 'System.Collections.Generic.List`1[System.Int32]'” 使用 ToListAsync() 时无法将类型为“System.String”的 object 转换为类型“System.Int32” - Unable to cast object of type 'System.String' to type 'System.Int32' while using ToListAsync() 类型'System.Int16'的对象不能转换为类型'System.Nullable`1 [System.Int32] - Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32] C#:无法将“System.Int64”类型的对象转换为“System.Int32”类型 - C#: Unable to cast object of type 'System.Int64' to type 'System.Int32' Expression.Convert:'System.Int64'类型的对象无法转换为'System.Int32'类型 - Expression.Convert: Object of type 'System.Int64' cannot be converted to type 'System.Int32' 无法将类型为“ System.Int64”的对象转换为类型为“ System.Int32”的对象 - Unable to cast object of type 'System.Int64' to type 'System.Int32' 无法将 System.Int64 类型的 object 转换为 System.Int32 类型 - Unable to cast object of type System.Int64 to type System.Int32 Entityframework 核心无法将类型为“System.Int32”的 object 转换为类型“System.Int64” - Entityframework Core Unable to cast object of type 'System.Int32' to type 'System.Int64' GetType返回Int而不是System.Int32 - GetType return Int instead of System.Int32
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM