How to make a shallow copy of an array?

后端 未结 9 734
梦如初夏
梦如初夏 2020-11-27 22:21

I pass a two-dimensional array as a property to my user control. There I store this values in another two-dimensional array:

int[,] originalValues = this.Met         


        
9条回答
  •  难免孤独
    2020-11-27 22:35

    If you want to deep copy an array of reference types, you can do this methodology:

    Implement IClonable iterface for your class and do your deep copy of all value typed fields inside to another constructed object.

    class A: ICloneable {
         int field1;
         public object Clone()
            {
                A a= new A();
                //copy your fields here 
                a.field1 = this.field1;
                ...
            }
    }
    

    Then you can do the actual copy using

    A[] array1 = new A[]{....};
    A[] array2 = array1.Select(a => a.Clone()).ToList();
    

提交回复
热议问题