Employee emp = new Employee()和emp = new Employee()

List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.FirstName = "Jack";
emp.LastName = "Ma";
emp.Salary = 20000;
employees.Add(emp);

emp.FirstName = "Tony";
emp.LastName = "Ma";
emp.Salary = 12000;
employees.Add(emp);

在这里往employees中插入多个Employee对象。如果在插入后面的emp时,使用同一个对象emp,会使得插入到employees里的对象全部都具有相同的值,也就是后插入的对象值会覆盖之前的对象值。

解决方法是,在使用同名对象前,先创建一个匿名对象,然后将该匿名对象赋值给emp。使用emp = new Employee()

List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.FirstName = "Jack";
emp.LastName = "Ma";
emp.Salary = 20000;
employees.Add(emp);

emp = new Employee();
emp.FirstName = "Tony";
emp.LastName = "Ma";
emp.Salary = 12000;
employees.Add(emp);

 

posted @ 2017-12-20 12:54  褐色鸟群  阅读(484)  评论(0编辑  收藏  举报