需要对引用类型的行为进行一些澄清
Need some clarification about reference type's behavior
我看过Difference between a Value Type and a Reference Type,在这篇文章中,作者是这样说的:
Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value
根据上面的引述,我预计下面的代码会将一个引用变量分配给另一个,不会复制数据,但它确实也在复制数据。你能帮我理解一下吗?
Class1 i1 = new Class1();
i1.Name = "Name1";
Class1 i2 = i1;
//i2.Name is "Name1"
对于 i2
我预计它指的是与正确的 i1
值相同的堆位置,但根据文章,不应复制数据。另外我的问题不应该被标记为重复,因为我知道值和引用类型之间的区别,我只需要澄清一下引用类型以及 deep copy/clone/shallow 的用法是什么,如果我们可以简单地使用赋值?
引用只是指向对象的指针。这样做只是复制参考。如果您这样做 i2.Name = "foobar";
i1.Name
也会更改为 foobar
。
For i2 I expected it refers to the same location of the heap as the i1
value that is right
正确,它们指的是内存中的相同位置。
but based on the article the data should not be copied.
再次更正,数据没有被复制,我们一起上图:
_ _ _ _
| |
i1 - - - -| addr |
|_ _ _ _|
现在,当您执行 Class1 i2 = i1;
时,您实际上是在复制 i1
的引用并将其分配给 i2
,您可以将其可视化为:
_ _ _ _
| |
i1 - - - -| addr |
|_ _ _ _|
/
/
/
i2 /
因此 i1.Name
和 i2.Name
具有相同的名称,因为 i1
和 i2
都引用内存中的同一个对象。
我看过Difference between a Value Type and a Reference Type,在这篇文章中,作者是这样说的:
Because reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second copy of the reference, which refers to the same location of the heap as the original value
根据上面的引述,我预计下面的代码会将一个引用变量分配给另一个,不会复制数据,但它确实也在复制数据。你能帮我理解一下吗?
Class1 i1 = new Class1();
i1.Name = "Name1";
Class1 i2 = i1;
//i2.Name is "Name1"
对于 i2
我预计它指的是与正确的 i1
值相同的堆位置,但根据文章,不应复制数据。另外我的问题不应该被标记为重复,因为我知道值和引用类型之间的区别,我只需要澄清一下引用类型以及 deep copy/clone/shallow 的用法是什么,如果我们可以简单地使用赋值?
引用只是指向对象的指针。这样做只是复制参考。如果您这样做 i2.Name = "foobar";
i1.Name
也会更改为 foobar
。
For i2 I expected it refers to the same location of the heap as the i1 value that is right
正确,它们指的是内存中的相同位置。
but based on the article the data should not be copied.
再次更正,数据没有被复制,我们一起上图:
_ _ _ _
| |
i1 - - - -| addr |
|_ _ _ _|
现在,当您执行 Class1 i2 = i1;
时,您实际上是在复制 i1
的引用并将其分配给 i2
,您可以将其可视化为:
_ _ _ _
| |
i1 - - - -| addr |
|_ _ _ _|
/
/
/
i2 /
因此 i1.Name
和 i2.Name
具有相同的名称,因为 i1
和 i2
都引用内存中的同一个对象。