C# Modifying Reference Type Objects doesn't reflect changes

≡放荡痞女 提交于 2019-12-24 20:15:50

问题


I have this C# code:

int i = 20;

object t = i;

object r = t;

r = 100;

Why at this point, the value of T is still 20 and not 100 ?

I supposed T and R pointed to the same location and changes to any of them should affect each other...

I can't really understand how reference types work in the Heap, please help me


回答1:


Why at this point, the value of T is still 20 and not 100 ?

Because you didn't modify t.

You'll want to look up "boxing". But, what's going on in your code is that the value 20 stored in i is "boxed", which means a new reference type object is allocated and the value 20 is copied into that object.

When you assign r = t, you copy the reference of that boxed value to t. So far, so good.

But, when you assign r = 100;, you have not modified the boxed value. The original boxed value remains the same, but now is referenced only by t.

The assignment r = 100 creates a whole new boxed value, allocated on the heap, and copies the reference to that object into the variable r. This has no effect on t, which remains set to the reference of the first boxed value of 20.




回答2:


When you set integer value i to an object t, boxing occurs and integer value inside a box put into Heap.

When you set t as r = t, at that time they point to same reference address on the Heap. But when you set r like r = 100 with a new integer value, new boxing occurs and r will be pointing to a different address.

First of all, boxing and unboxing is very costly thing. Why are you trying to set integer to object?

If you want to pass integer to some method and get changed value you can use ref keyword in the method argument.

Here below you can find sample code:

    public int GetValue() {
        int i = 20;
        SetNewValue(ref i);
        return i;
    }

    public void SetNewValue(ref int value) {
        value = 100;
    }


来源:https://stackoverflow.com/questions/46986774/c-sharp-modifying-reference-type-objects-doesnt-reflect-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!