装箱和拆箱,为什么输出不是“System.Object”?
我得到以下代码:
object var3 = 3;
Console.WriteLine(var3.GetType().ToString());
Console.WriteLine(typeof(object).ToString());
输出是:
System.Int32
System.Object
为什么它们不是 System.Object
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
GetType()
函数返回变量中实例的实际类型。即使您的变量被声明为
object
,它实际上持有一个装箱的Int32
实例。The
GetType()
function returns the actual type of the instance in the variable.Even though your variable is declared as
object
, it's actually holding a boxedInt32
instance.如果您问为什么 boxedObject.GetType() 不返回 Object..查看 .com/en-us/library/yz2be5wk.aspx" rel="nofollow noreferrer">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
忽略装箱主题,所有类都继承自类型对象。对于引用类型和值类型都是如此。 GetType 显示最派生的类型,在本例中为 System.Int32。
GetType 将返回 System.Object 的少数情况之一是如果执行以下操作:
装箱是指引用类型指向值类型的情况。通常,这是作为 System.Object 引用完成的。 TypeOf 将返回最派生的实际类型,而不是引用类型。
GetType 将为这些类型做类似的事情。
Ignoring the topic of boxing, all classes inherit from type object. This is true for both reference types and value types. GetType shows the most derived type, which in this case is System.Int32.
One of the few times GetType is going to return System.Object is if you do this:
Boxing refers to when a value type is pointed to by a reference type. Generally this is done as a System.Object reference. TypeOf will return the most derived actual type, not the reference type.
GetType will do similar things for these types.
这实际上与拳击无关;而是关于拳击。这是关于
GetType
的行为。它返回变量值的类型,而不是声明变量的类型:也不会返回
System.Object
。This isn't really about boxing; this is about the behaviour of
GetType
. It returns the type of the value of the variable, not the type the variable was declared with:won't return
System.Object
either.变量的声明只是编译时的信息,而方法的执行是运行时的。换句话说,GetType() 无法知道对象被声明的类型,因为它只能在运行时知道对象的实际类型。
类似,如果您调用
bInstance.GetType() 则无法知道该变量被声明为类型“a”,并且我认为您也不希望它在这种情况下返回“a”。然而,在上面的示例中,a 是我的 object 缩写,b 是 System.Int32
declarations of variable is compile time only information whereas method execution is runtime. In other words there's no way GetType() can know what type the object was declared as it can only know the actual type of the object at runtime.
similar if you had
the call to bInstance.GetType() have no way of knowing that the variable was declared as type 'a' and I don't think you expect it to return 'a' in this case either. However in the example above a is my abbreviation of object and b is for System.Int32