有关值类型的拳击混乱 [英] Confusion regarding boxing of value types
问题描述
在下面的代码...
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 variableo
that the5
represented by the variablei
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 ino
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 onobject
which means that the implementation that is called depends on the runtime type, not the static type. Sinceint
overridesToString
with its own implementation, it isint.ToString
that is called, not the default implementation provided byobject
.object o = 5; Console.WriteLine(o.GetType()); // outputs System.Int32, not System.Object
这篇关于有关值类型的拳击混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!