【问题标题】:Array.Clone() performs deep copy instead of shallow copyArray.Clone() 执行深拷贝而不是浅拷贝
【发布时间】:2018-02-26 04:53:03
【问题描述】:

我读过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

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

    标签: c# clone shallow-copy


    【解决方案1】:

    因为这是一个浅拷贝 newArr 应该参考 arr

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

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

    【讨论】:

      【解决方案2】:

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

      示例(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);
          }
      }
      

      【讨论】:

        【解决方案3】:

        复制不可变结构的集合时(诸如它的基元是不可变的),深复制和浅复制没有区别。它们是按值复制的 - 因此它就像深复制一样。

        查看更多区别:What is the difference between a deep copy and a shallow copy?

        【讨论】:

        • 一个更好的描述应该是“复制不可变对象的集合时,深拷贝和浅拷贝没有区别。”,所有原语都是不可变的,但您可以在任何纯不可变集合上看到相同的行为对象。
        • 考虑一下,您需要说“不可变结构”才能使答案的第二部分为真。从技术上讲,不可变类的行为仍会有所不同,因为内存中只有一个不可变对象的副本。
        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2016-09-27
          • 2010-11-19
          • 1970-01-01
          • 2012-04-12
          • 1970-01-01
          • 2015-01-13
          • 2011-09-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多