如何在C#中复制一个类对象

Par*_*tha 0 c# object

根据我在C#中的理解,当一个对象被分配给另一个相同类型的对象时,它的引用被复制而不是值.所以我想知道如何将一个对象分配给另一个对象,使其值被复制而不被引用到第二个对象.

Raw*_*aew 5

您可以看到test2.ErrorDetail更改为"DTL2",而test1.ErrorDetail仍为"DTL1".

    public class TestClone : ICloneable
    {
        public bool IsSuccess { get; set; }
        public string ErrorCode { get; set; }
        public string ErrorDetail { get; set; }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }

    static void Main(string[] args)
    {
        var test1 = new TestClone() { IsSuccess = true, ErrorCode = "0", ErrorDetail = "DTL1" };
        var test2 = (TestClone) test1.Clone();
        test2.ErrorDetail = "DTL2";
    }
Run Code Online (Sandbox Code Playgroud)

  • 尤伯杯.然而,目前还不清楚OP是否想要_deep cloning_,这是你答案中没有提到的 (2认同)