Array.Clone() 执行深拷贝而不是浅拷贝

Array.Clone() performs deep copy instead of shallow copy

我读过 Array.Clone performs shallow copy,但是这段代码表明创建了原始数组的深层副本,即克隆数组中的任何更改都不会反映在原始数组中

int[] arr = new int[] { 99, 98, 92, 97, 95 };
int[] newArr = (int[])arr.Clone();
//because this is a shallow copy newArr should refer arr
newArr[0] = 100;
//expected result 100
Console.WriteLine(arr[0]);//print 99

我是不是遗漏了什么明显的东西?

尝试使用相同的代码,但 class 的 属性 是一个整数。由于数组元素是值类型,因此克隆数组的元素是它们自己的“实例”。

示例 (DotNet Fiddle):

using System;
                    
public class Program
{
    class SomeClass {
   
        public Int32 SomeProperty { get; set; }

    }
    
    public static void Main()
    {
        SomeClass[] arr = new [] {
            new SomeClass { SomeProperty = 99 },
            new SomeClass { SomeProperty = 98 },
            new SomeClass { SomeProperty = 92 },
            new SomeClass { SomeProperty = 97 },
            new SomeClass { SomeProperty = 95 }
        };
        
        SomeClass[] newArr = (SomeClass[])arr.Clone();
        
        newArr[0].SomeProperty = 100;
        
        Console.WriteLine(arr[0].SomeProperty);
    }
}

当复制一组不可变结构(诸如它的基元是不可变的)时,深拷贝和浅拷贝之间没有区别。它们按值复制 - 因此它与深度复制执行的一样。

在下面查看更多差异:What is the difference between a deep copy and a shallow copy?

because this is a shallow copy newArr should refer arr

不,数组及其元素被复制。但是不会复制对元素中对象的引用。

文案只下降了一层:因此很浅。深拷贝会克隆所有引用的对象(但这不能用整数显示。)

在一些高级的Array或List<>中真的很难只用Array.Clone() 请改用我开发的 FastDeepCloner 之类的插件。它将以侵入方式克隆对象。

var newArr= FastDeepCloner.DeepCloner.Clone(arr);