如果我有类似下面的代码,我该如何装箱和拆箱? [英] How do I box and unbox if I have something like below codes?

查看:97
本文介绍了如果我有类似下面的代码,我该如何装箱和拆箱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白了

  int  i =  123 < /跨度>; 
object o =( object )i; // 拳击
o = 123 ;
i =( int )o; // 拆箱





但是如果我有类似的东西我可以装箱和拆箱

<前lang =c#> int i = < span class =code-digit> 123 ;
int y;
MyObject obj = new MyObject():

解决方案

这个问题毫无意义,因为在第二种情况下你没有解释什么是盒子和unbox,没有显示类型的定义 MyObject 并没有解释你想要存在什么。如果此类型是值类型,则可以通过分配给某些对象变量来将其打包;如果没有,则样本与装箱无关,并且在两种情况下,代码与 i y



在第一个示例中,类型转换对象 o =(对象)i; 完全是多余的,应该是 o = i; 这是因为一切都是对象,包括 i



-SA


I understood

int i = 123;
object o = (object)i;  // boxing
o = 123;
i = (int)o;  // unboxing



But how to I box and unbox if I have something like

int i = 123;
int y;
MyObject obj = new MyObject():

解决方案

The question makes no sense because you did not explain what to box and unbox in second case, did not show the definition of the type MyObject and did not explain what you want to exist. If this type is a value type, you can box it by assigning to some object variable; if not, the sample is unrelated to boxing, and, in both cases, the code has nothing to do with i or y.

In first sample, the type cast object o = (object)i; is totally redundant, should be o = i; this is because everything is object, including i.

—SA


这篇关于如果我有类似下面的代码,我该如何装箱和拆箱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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