這是必須引用開放類的列表。將新對象添加到列表中時,以前添加的所有對象都將被覆蓋
readonly List<object> openedClasses = new List<object>();
這裏是我創建類並添加列表的地方。
var employees = myWs.ReturnListEmployee(guid);
foreach (Api.EmployeeData employee in employees)
{
openedClasses.Add(new MyClass(pendingSchedules[0], employee));
}
我的階級和它的構造:
class MyClass
{
public Schedule schedule;
public MyClass(Schedule schedule, Api.EmployeeData employee)
{
// the "schedule.EmployeeData" it is constantly changed
this.schedule = schedule;
this.schedule.EmployeeData = employee;
}
}
我的問題是:每個foreach循環的所有值以前添加到列表由最近添加類覆蓋。
我試過了我在互聯網上找到的所有解決方案並做了檢查,該類不是靜態的,而且我移除了每個被調用的靜態方法和靜態字段(只是爲了確保),列表I已經創建,並且沒有隻讀作爲「對象」列表和「MyClass」列表。
有了:
openedClasses.Add(new MyClass(pendingSchedules[0], employee));
而且具有:
var myClass = new MyClass(pendingSchedules[0], employee);
openedClasses.Add(myClass);
所有'MyClass'實例引用相同的'Schedule'對象,所以每次有人將其'EmployeeData'財產,所有其他實例也受到影響 –