【发布时间】:2019-11-29 06:55:12
【问题描述】:
下面是我在Visual Studio 2019 Mac中运行的c#代码,结果让我有点意外:
using System;
namespace Test
{
public struct Point
{
public int x;
private int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(100, 100);
Point p2;
p2 = p1;
p1.x = 200;
Console.WriteLine("p1.x is {0},p2.x is {1} ", p1.x, p2.x);
// I think here should Output: p1.x is 200, p2.x is 200
// But the actual output is: p1.x is 200, p2.x is 100, why? is it a reference copy?
// p1 and p2 should share the same reference, right?
}
}
}
实际上,当我阅读 C# 指令时,它解释了这样的代码应该输出: p1.x 是 200,p2.x 是 200 因为 p2 和 p1 共享相同的指针来指向堆中的一个地址,对吗?而当我尝试在 VS2019 Mac 中测试上述代码时。它的输出是: p1.x 是 200,p2.x 是 100 这让我很困惑? 是浅拷贝还是深拷贝? 有人可以解释为什么 p1.x 仍然是 100,而 p1.x 已经变为 200 吗? 非常感谢。
【问题讨论】:
标签: c# copy deep-copy shallow-copy