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

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

问题描述

所以我明白装箱和拆箱是什么.它什么时候出现在现实世界的代码中,或者在哪些例子中是一个问题?我无法想象做这样的事情:

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.

以前,我们会:

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天全站免登陆