有关值类型的拳击混乱 [英] Confusion regarding boxing of value types

查看:253
本文介绍了有关值类型的拳击混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码...

  INT I = 5; 
对象o = 5;
Console.WriteLine(O); //输出5



我有三个问题:



1)什么额外的/有用的功能是通过收购 5 居住在变量 0 5 通过该变量我没有?



2)如果一些代码期待值类型,那么我们就可以通过它的INT I ,但如果期望引用类型,它可能不会在5兴趣盒装0 反正。所以,当被装箱转换明确在代码中使用?



3)如何来的 Console.WriteLine(O)打印出5而不是System.Object的??


解决方案

哪些附加/有用的功能是由5侨收购在变量o是由变量表示的5 I没有?




这是罕见的,你的希望的框的东西,但有时它的必要这样做。在旧版本的.NET拳常常必要的,因为一些方法只适用对象(例如ArrayList中的方法)的工作。这是少得多的问题,现在有仿制药,所以拳击发生在新的代码较少。




如果一些代码期待一个值类型,那么我们就可以通过它的INT I,但如果期望引用类型,它可能不会在邻反正盒装5感兴趣。所以,当被装箱转换明确在代码中使用?




在实践中通常拳为你自动发生。如果你想更清楚你的代码的读者,拳击正在发生的事情,你可以明确地框的变量。这可能是相关的,如果性能可能是一个问题。




为什么Console.WriteLine命令(O)打印出5,而不是系统。对象??




由于的ToString 是一个虚拟的方法对象这意味着被调用的实现依赖于运行时类型,而不是静态类型。由于 INT 覆盖的ToString 与它自己的实现,这是 int.ToString 被称为由,而不是默认实现对象。

 对象o = 5; 
Console.WriteLine(o.GetType()); //输出System.Int32,而不是System.Object的


In the following code...

 int i=5;  
 object o = 5;
 Console.WriteLine(o); //prints 5

I have three questions:

1) What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?

2) If some code is expecting a value type then we can just pass it the int i , but if its expecting a reference type , its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?

3) How come the Console.WriteLine(o) print out a 5 instead of System.Object ??

解决方案

What additional/useful functionality is acquired by the 5 residing in the variable o that the 5 represented by the variable i does not have ?

It's rare that you want to box something, but occasionally it is necessary to do so. In older versions of .NET boxing was often necessary because some methods only worked with object (e.g. ArrayList's methods). This is much less of a problem now that there is generics, so boxing occurs less frequently in newer code.

If some code is expecting a value type then we can just pass it the int i, but if its expecting a reference type, its probably not interested in the 5 boxed in o anyway . So when are boxing conversions explicitly used in code ?

In practice boxing usually happens automatically for you. You could explicitly box a variable if you want to make it more clear to the reader of your code that boxing is happening. This might be relevant if performance could be an issue.

How come the Console.WriteLine(o) print out a 5 instead of System.Object ??

Because ToString is a virtual method on object which means that the implementation that is called depends on the runtime type, not the static type. Since int overrides ToString with its own implementation, it is int.ToString that is called, not the default implementation provided by object.

object o = 5;
Console.WriteLine(o.GetType());  // outputs System.Int32, not System.Object

这篇关于有关值类型的拳击混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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