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

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

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

13条回答
  •  眼角桃花
    2020-12-02 07:22

    Please note: There is a difference between using String[] to StringBuilder[].

    In String - if you change the String, the other arrays we have copied (by CopyTo or Clone) that points to the same string will not change, but the original String array will point to a new String, however, if we use a StringBuilder in an array, the String pointer will not change, therefore, it will affect all the copies we have made for this array. For instance:

    public void test()
    {
        StringBuilder[] sArrOr = new StringBuilder[1];
        sArrOr[0] = new StringBuilder();
        sArrOr[0].Append("hello");
        StringBuilder[] sArrClone = (StringBuilder[])sArrOr.Clone();
        StringBuilder[] sArrCopyTo = new StringBuilder[1];
        sArrOr.CopyTo(sArrCopyTo,0);
        sArrOr[0].Append(" world");
    
        Console.WriteLine(sArrOr[0] + " " + sArrClone[0] + " " + sArrCopyTo[0]);
        //Outputs: hello world hello world hello world
    
        //Same result in int[] as using String[]
        int[] iArrOr = new int[2];
        iArrOr[0] = 0;
        iArrOr[1] = 1;
        int[] iArrCopyTo = new int[2];
        iArrOr.CopyTo(iArrCopyTo,0);
        int[] iArrClone = (int[])iArrOr.Clone();
        iArrOr[0]++;
        Console.WriteLine(iArrOr[0] + " " + iArrClone[0] + " " + iArrCopyTo[0]);
       // Output: 1 0 0
    }
    

提交回复
热议问题