C# 修改引用类型对象不反映更改 [英] C# Modifying Reference Type Objects doesn't reflect changes
问题描述
我有这个 C# 代码:
I have this C# code:
int i = 20;
object t = i;
object r = t;
r = 100;
为什么此时 T 的值仍然是 20 而不是 100 ?
我认为 T 和 R 指向同一个位置,对它们中的任何一个进行更改都会相互影响...
I supposed T and R pointed to the same location and changes to any of them should affect each other...
我真的无法理解 Heap 中的引用类型是如何工作的,请帮帮我
I can't really understand how reference types work in the Heap, please help me
推荐答案
为什么此时 T 的值仍然是 20 而不是 100 ?
Why at this point, the value of T is still 20 and not 100 ?
因为你没有修改t
.
您需要查找 "拳击".但是,您的代码中发生的事情是存储在 i
中的值 20
被装箱",这意味着分配了一个新的引用类型对象,并且值 20
被复制到那个对象中.
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.
当您分配 r = t
时,您将该装箱值的引用复制到 t
.到目前为止,一切都很好.
When you assign r = t
, you copy the reference of that boxed value to t
. So far, so good.
但是,当您分配 r = 100;
时,您没有修改了装箱值.原始装箱值保持不变,但现在仅被 t
引用.
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
.
赋值 r = 100
创建一个全新的装箱值,分配在堆上,并将对该对象的引用复制到变量 r
中.这对 t
没有影响,它仍然设置为 20
的第一个装箱值的引用.
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
.
这篇关于C# 修改引用类型对象不反映更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!