装箱和拆箱:什么时候它来呢? [英] Boxing and unboxing: when does it come up?

查看:319
本文介绍了装箱和拆箱:什么时候它来呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我明白了什么装箱和拆箱的。当是它拿出在现实世界code或什么的例子是一个问题?我不能想象做这样的事情例如:

So I understand what boxing and unboxing is. When's it come up in real-world code, or in what examples is it an issue? I can't imagine doing something like this example:

int i = 123;
object o = i;           // Boxing
int j = (int)o; 	// Unboxing

...但是,这几乎可以肯定非常过于简单,我可能甚至做装箱/拆箱之前不知道它。

...but that's almost certainly extremely oversimplified and I might have even done boxing/unboxing without knowing it before.

推荐答案

这是的不再是一个问题现在比前泛型。现在,例如,我们可以使用:

It's much less of an issue now than it was prior to generics. Now, for example, we can use:

List<int> x = new List<int>();
x.Add(10);
int y = x[0];

没有拳击或拆箱需要在所有。

No boxing or unboxing required at all.

previously,我们希望有:

Previously, we'd have had:

ArrayList x = new ArrayList();
x.Add(10); // Boxing
int y = (int) x[0]; // Unboxing

这是我的的装箱和拆箱的最常见的经验,至少。

That was my most common experience of boxing and unboxing, at least.

没有泛型介入,我想我可能会说,反思是拳在我工作的项目中最常见的原因。反射的API始终使用对象的东西像一个方法的返回值 - 因为他们知道用什么的没有别的办法

Without generics getting involved, I think I'd probably say that reflection is the most common cause of boxing in the projects I've worked on. The reflection APIs always use "object" for things like the return value for a method - because they have no other way of knowing what to use.

这可能赶上你,如果你不知道它的另一个原因是,如果你使用它实现一个接口的值类型和值传递到具有接口类型作为参数的另一种方法。同样,泛型使这个问题不大,但如果你没有意识到这一点它可以是一个讨厌的惊喜。

Another cause which could catch you out if you're not aware of it is if you use a value type which implements an interface, and pass that value to another method which has the interface type as its parameter. Again, generics make this less of a problem, but it can be a nasty surprise if you're not aware of it.

这篇关于装箱和拆箱:什么时候它来呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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