【问题标题】:in c# code why below copy didn't work as reference copy? [duplicate]在 c# 代码中,为什么下面的副本不能作为参考副本? [复制]
【发布时间】: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


    【解决方案1】:

    您的Pointstruct。当您将p2 分配给p1 时,p2 变成了一个副本。我想你可能想在value types versus reference types 上阅读更多内容。

    【讨论】:

      【解决方案2】:

      结构是 C# 中的值类型,这意味着它们将按值分配。这意味着当您将p1 分配给p2 时,它会复制值而不是内存位置。如果您希望它具有您正在寻找的行为,请将您的观点设为一个类。类是引用类型。

      【讨论】:

        猜你喜欢
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-22
        相关资源
        最近更新 更多