经常我们会发现,当我们把一个对象列表赋值给另一个对象列表之后,一个改变了,另一个
也跟着改变了,但是这往往不是我们想看到的
那么,怎么办呢?
办法只有一个,那就是让你的对象实现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( " -------------------------------------------------------------------- "); Console.WriteLine(); 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( " -------------------------------------------------------------------- "); Display(srcEmployeeList); Console.WriteLine( " -------------------------------------------------------------------- "); Console.WriteLine(); Console.WriteLine(); Console.WriteLine( " Dest Employee List: "); Console.WriteLine( " -------------------------------------------------------------------- "); Display(dstEmployeeList); Console.WriteLine( " -------------------------------------------------------------------- "); } private void Display(IList<Employee> employeeList) { foreach (Employee employee in employeeList) { Console.WriteLine(employee); } }
运行结果:
Source Employee List After Change:
--------------------------------------------------------------------Employee ID: 1First Name: LynnLast Name: Huang......
Dest Employee List:
--------------------------------------------------------------------Employee ID: 1First Name: NancyLast Name: Davolio......