在 C# 代码中,为什么下面的副本不能用作参考副本?
in c# code why below copy didn't work as reference copy?
在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
哪个让我如此困惑?
是浅拷贝还是深拷贝?
有人可以解释为什么 p2.x 仍然是 100,而 p1.x 已经变成 200 了吗?
非常感谢。
您的 Point
是 struct
。当您将 p2
分配给 p1
时,p2
成为副本。我想你可能想多读一点 value types versus reference types。
结构是 C# 中的值类型,这意味着它们将按值分配。这意味着当您将 p1
分配给 p2
时,它正在复制值而不是内存位置。如果您希望它具有您正在寻找的行为,请将您的观点设为 class。 类 是引用类型。
在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 哪个让我如此困惑? 是浅拷贝还是深拷贝? 有人可以解释为什么 p2.x 仍然是 100,而 p1.x 已经变成 200 了吗? 非常感谢。
您的 Point
是 struct
。当您将 p2
分配给 p1
时,p2
成为副本。我想你可能想多读一点 value types versus reference types。
结构是 C# 中的值类型,这意味着它们将按值分配。这意味着当您将 p1
分配给 p2
时,它正在复制值而不是内存位置。如果您希望它具有您正在寻找的行为,请将您的观点设为 class。 类 是引用类型。