Why does copy of the List still change properties in the original List using C#

后端 未结 6 1673
不知归路
不知归路 2021-01-21 02:49

Lets say I have this class

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool isActive {          


        
6条回答
  •  悲哀的现实
    2021-01-21 03:44

    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 Employees = new List();
        Employees.Add(new Employee { FirstName = "firstname", LastName = "lastname", isActive = true });
        List 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;
            }
        }
    

提交回复
热议问题