天天看點

淺談對象的深度拷貝 - IClonable接口

經常我們會發現,當我們把一個對象清單指派給另一個對象清單之後,一個改變了,另一個

也跟着改變了,但是這往往不是我們想看到的

那麼,怎麼辦呢?

辦法隻有一個,那就是讓你的對象實作IClonable接口

對象代碼:

public class Employee : ICloneable

    {

        public int EmployeeID { get; set; }

        public string LastName { get; set; }

        public string FirstName { get; set; }

        public string Title { get; set; }

        public string City { get; set; }

        public string Region { get; set; }

        public string Country { get; set; }

        public string Notes { get; set; }

        public override string ToString()

        {

            string format = "Employee ID: {0}\nFirst Name: {1}\n"

                          + "Last Name: {2}\nTitle: {3}\nCity: {4}\n"

                          + "Region: {5}\nCountry: {6}\nNotes: {7}\n";

            return string.Format(format, EmployeeID, FirstName, LastName, Title, City, Region, Country, Notes);

        }

        public Object Clone()

        {  

            Employee cloned = new Employee();

            cloned.EmployeeID = this.EmployeeID;

            cloned.LastName = this.LastName;

            cloned.FirstName = this.FirstName;

            cloned.Title = this.Title;

            cloned.City = this.City;

            cloned.Region = this.Region;

            cloned.Country = this.Country;

            cloned.Notes = this.Notes;

            return cloned;  

    }

測試代碼如下:

public void Run()

            EmployeesClient employeeClient = new EmployeesClient();

            List<Employee> srcEmployeeList = employeeClient.GetAllEmployees();

            Console.WriteLine("Source Employee List:");

            Console.WriteLine("--------------------------------------------------------------------");

            Display(srcEmployeeList);

            Console.WriteLine();

            List<Employee> dstEmployeeList = new List<Employee>();

            srcEmployeeList.ForEach(emp => dstEmployeeList.Add((Employee)emp.Clone()));

            srcEmployeeList[0].LastName = "Huang";

            srcEmployeeList[0].FirstName = "Lynn";

            Console.WriteLine("Source Employee List After Change:");

            Console.WriteLine("Dest Employee List:");

            Display(dstEmployeeList);

        private void Display(IList<Employee> employeeList)

            foreach (Employee employee in employeeList)

            {

                Console.WriteLine(employee);

            }

運作結果:

Source Employee List After Change:

--------------------------------------------------------------------

Employee ID: 1

First Name: Lynn

Last Name: Huang

......

Dest Employee List:

First Name: Nancy

Last Name: Davolio