我有以下代码:
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属性。
我需要一种方法将员工添加到Department.Employees保留基本属性。来自你们的任何想法,而不涉及基类。
仅供参考:将基类属性移动到employee类不是一种选择。
答案 0 :(得分:2)
如果您描述的行为确实与您发布的代码一起出现,那么只有一个结论:
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);
}
答案 1 :(得分:0)
尝试这样做,让我们知道它是否有效:
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)
}