Difference between the System.Array.CopyTo() and System.Array.Clone()

前端 未结 13 2179
攒了一身酷
攒了一身酷 2020-12-02 06:50

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

13条回答
  •  广开言路
    2020-12-02 07:21

    object[] myarray = new object[] { "one", 2, "three", 4, "really big number", 2324573984927361 };
    
    //create shallow copy by CopyTo
    //You have to instantiate your new array first
    object[] myarray2 = new object[myarray.Length];
    //but then you can specify how many members of original array you would like to copy 
    myarray.CopyTo(myarray2, 0);
    
    //create shallow copy by Clone
    object[] myarray1;
    //here you don't need to instantiate array, 
    //but all elements of the original array will be copied
    myarray1 = myarray.Clone() as object[];
    
    //if not sure that we create a shalow copy lets test it
    myarray[0] = 0;
    Console.WriteLine(myarray[0]);// print 0
    Console.WriteLine(myarray1[0]);//print "one"
    Console.WriteLine(myarray2[0]);//print "one"
    

    the source

提交回复
热议问题