拳击VS拆箱 [英] Boxing vs Unboxing

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

问题描述

另外最近C#面试问题我是,如果我知道什么装箱和拆箱的。
我解释说,值类型在堆栈和引用类型上堆。
当值转换为引用类型,我们把它叫做拳,反之亦然。



然后他问我来计算的:

  INT I = 20; 
对象J =;
J = 50;



什么是 I



我搞砸了,说50,在那里它实际上20.现在我想明白为什么,但是当我用不同的组合我很惊讶看到这样打:

 对象A = 1; //拳击
对象B = A; //引用堆栈指针堆
A = 2这两个对象; //拳击



我期待看到 B == 2 为好,但它不是,为什么?是不是因为第二拳破坏并替换堆上整个 A 对象?



因为如果我这样做,它的罚款:

 公共类TT 
{
公众诠释X;
}

TT T =新TT();
t.x = 1;
TT T2 =新TT();
t2.x = 2;
t = t2时;
t.x = 3;



什么是 t2.x ?它应该是3,这是。但是,这不是装箱/拆箱的例子可言,这是正确的?所以,你会怎么总结呢?



能值成为有史以来同在拳击/拆箱转换如上?


解决方案

  1. 您说得对第二次分配将替换第一个。它不改变已装箱值。


  2. 您例如没有使用拳。值(INT)存储为一个int,而不是盒装。


  3. 没有,拳击仍保持不变性的保证。



Another recent C# interview question I had was if I knew what Boxing and Unboxing is. I explained that value types are on Stack and reference types on Heap. When a value is cast to a reference type, we call it boxing and vice versa.

Then he asked me to calculate this:

int i = 20;
object j = i;
j = 50;

What is i?

I messed it up and said 50, where its actually 20. Now I think understand it why, however when I was playing with different combinations I was surprised to see this:

Object a = 1; // Boxing
Object b = a; // referencing the pointer on stack to both objects on heap
a = 2; // Boxing

I was expecting to see b == 2 as well, but it isn't, why? Is it because the second boxing destroys and replaces the whole a object on the heap?

Because if I do this, it's fine:

public class TT
{
    public int x;
}

TT t = new TT();
t.x = 1;
TT t2 = new TT();
t2.x = 2;
t = t2;
t.x = 3;

What is t2.x? It should be 3, and it is. But this is not an example of boxing / unboxing at all, is this correct? So how would you summarize this?

Could the values ever become the same in a boxing/unboxing conversion as above?

解决方案

  1. You're right the second assignment replaces the first. It doesn't change the boxed value.

  2. Your example doesn't make use of boxing. The value (int) is stored as an int and not boxed.

  3. No, boxing still keeps the immutability guarantee.

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

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