C# 陣列的複製

iamzxf發表於2015-04-22


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace arrayClone
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }        
    }

    class Program
    {
        static void Main(string[] args)
        {
            int[] nArray1 = { 1, 2 };
            int[] nArray2 = nArray1;
            int[] nArray3 = (int[])nArray1.Clone();

            Console.WriteLine(object.ReferenceEquals(nArray1,nArray2));
            Console.WriteLine(object.ReferenceEquals(nArray1, nArray3));
            
            nArray1[0] = 100;
            Console.WriteLine(nArray1[0]);
            Console.WriteLine(nArray2[0]);
            Console.WriteLine(nArray3[0]);

            Person[] personArray1 ={
                            new Person("zxf",23),
                            new Person("lisi",33),
                            };

            Person[] personArray2 = personArray1;
            Person[] personArray3 = (Person[])personArray1.Clone();

            personArray1[0].Name = "zhang";
            Console.WriteLine(personArray2[0].Name);
            Console.WriteLine(personArray3[0].Name);

            Console.WriteLine(object.ReferenceEquals(personArray1, personArray2));
            Console.WriteLine(object.ReferenceEquals(personArray2, personArray3));

            Console.ReadLine();
            

        }
    }
}



相關文章