在原来的列表,使用C#为什么名单的副本仍然更改属性 [英] Why does copy of the List still change properties in the original List using C#
本文介绍了在原来的列表,使用C#为什么名单的副本仍然更改属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有这个类
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool isActive { get; set; }
}
和使用这样的:
List<Employee> Employees = new List<Employee>();
Employees.Add(new Employee { FirstName = "firstname", LastName = "lastname", isActive = true });
List<Employee> EmployeesCopy = new List<Employee>(Employees);
EmployeesCopy[0].isActive = false;
为什么在 EmployeesCopy
的 isActive
属性还修改属性在原始列表改变?
Why does change in isActive
property of EmployeesCopy
also modify property in the original list?
推荐答案
由于新的列表仍旧引用同一个Employee对象。你可以做这样的事情创建新的一个新的列表:
Because the new list still contains references to the same employee objects. You can create new ones in a new list by doing something like this:
List<Employee> Employees = new List<Employee>();
Employees.Add(new Employee { FirstName = "firstname", LastName = "lastname", isActive = true });
List<Employee> EmployeesCopy = Employees.Select(x => new Employee(x)).ToList();
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool isActive { get; set; }
public Employee()
{ }
public Employee(Employee e)
{
FirstName = e.FirstName;
LastName = e.LastName;
isActive = e.isActive;
}
}
这篇关于在原来的列表,使用C#为什么名单的副本仍然更改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文