向列表中添加对象

本文关键字:对象 添加 列表 | 更新日期: 2023-09-27 17:55:01

我有以下代码:

public class BaseEmployee
{
   public bool Status {get;set;}
   public DateTime DateOfJoining {get;set;}
}
public class Employee : BaseEmployee
{
   public string Name {get;set;}
   public string City {get;set;}
   public string State {get;set;}
}

foreach(var record in records)
{
  var employee = GetDefaultBaseEmployeeProperties();
  employee.Name = record.Name
  employee.State = record.Name;
  employee.City = record.city;
  Department.Employess.Add(employee)
 }

当我这样做的时候,所有的员工都被更新为与最后添加的员工相同的姓名、城市和州。为了解决引用的问题,我使用了

 Department.Employees.Add(new Employee {
        Name = record.Name;
        City = record.City;
        State = record.State;
   });

但是这种方法的问题是,我在雇员对象中丢失了BaseEmployee属性。

我需要一种将员工添加到部门的方法。保留基本属性的雇员。在不触及基类的情况下,从你们的人那里得到任何想法。

仅供参考:不能将基类属性移动到employee类。

向列表中添加对象

如果你描述的行为真的发生在你发布的代码中,只有一个结论:

  • GetDefaultBaseEmployeeProperties()每次被调用时都返回相同的 Employee实例。

这很糟糕,正如你所看到的。修复GetDefaultBaseEmployeeProperties()使它每次返回一个新的 Employee实例。


编辑:如果您不能更改GetDefaultBaseEmployeeProperties(),您可以复制如下属性:

var template = GetDefaultBaseEmployeeProperties();
foreach(var record in records)
{
    var employee = new Employee();      // create a *new* Employee instance
    employee.Status = template.Status;  // copy default properties
    employee.DateOfJoining = template.DateOfJoining;
    employee.Name = record.Name;        // fill Employee with new values
    employee.State = record.State;
    employee.City = record.city;
    Department.Employees.Add(employee);
}

试着这样做,让我们知道它是否有效:

foreach(var record in records)
{
  var temp = record; // there is sometimes a bug with fireach iterators last item.
  var employee = GetDefaultBaseEmployeeProperties();
  employee.Name = temp .Name
  employee.State = temp.State;  // you have a bug here in your original code.
  employee.City = temp.city;
  Department.Employess.Add(employee)
 }