一个列表的更改如何影响完全不同的列表?
我有以下代码:
jobsToShiftUp.AddRange(PresentationManager.Instance.ScheduleViewSource.Where(o => o.Resources.First().ResourceName == criticalJob.Resources.First().ResourceName && ((o.Start >= criticalJob.Start) || (o.Start < criticalJob.Start && o.End > criticalJob.Start)) && !o.JobGuid.Equals(((Job)state.DraggedAppointments.First()).JobGuid) && GetWeekNumber(o.Start) == GetWeekNumber(criticalJob.Start)));
jobsToShiftUp = jobsToShiftUp.OrderBy(o => o.Start).ToList();
TimeSpan timeToShift = criticalJob.End - jobsToShiftUp.First().Start;
foreach (Job job in jobsToShiftUp)
{
if (jobsToShiftUp.IndexOf(job) == 0)
{
((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).Start += timeToShift;
((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).End += timeToShift;
......
最后两行(增加作业的开始和结束属性)同时影响 state.destinationappointmentssource 列表和 jobsToShiftUp 列表(即,它影响当前在foreach 循环)。我根本无法想象为什么它会影响 jobsToShiftUp 列表!?
I have the following code:
jobsToShiftUp.AddRange(PresentationManager.Instance.ScheduleViewSource.Where(o => o.Resources.First().ResourceName == criticalJob.Resources.First().ResourceName && ((o.Start >= criticalJob.Start) || (o.Start < criticalJob.Start && o.End > criticalJob.Start)) && !o.JobGuid.Equals(((Job)state.DraggedAppointments.First()).JobGuid) && GetWeekNumber(o.Start) == GetWeekNumber(criticalJob.Start)));
jobsToShiftUp = jobsToShiftUp.OrderBy(o => o.Start).ToList();
TimeSpan timeToShift = criticalJob.End - jobsToShiftUp.First().Start;
foreach (Job job in jobsToShiftUp)
{
if (jobsToShiftUp.IndexOf(job) == 0)
{
((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).Start += timeToShift;
((ObservableCollection<Job>)state.DestinationAppointmentsSource).Single(o => o.JobGuid.Equals(job.JobGuid)).End += timeToShift;
......
The last two lines (increasing the start and end properties of the jobs) affects both the state.destinationappointmentssource list AND the jobsToShiftUp list (i.e. it affects the job object currently being referenced in the foreach loop). I can't think why it would affect the jobsToShiftUp list at all!?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于两个列表都包含相同的对象实例。
例如:
list[0].Start+=10
会将 10 添加到job
中,该作业也被list2
引用Since both list contain the same instances of objects.
Like:
list[0].Start+=10
will add 10 tojob
which is also referenced bylist2
我认为这两个对象具有相同的引用。
因此,jobsToShiftUp 集合和 state.DestinationAppointmentsSource 可能都具有一些相同的引用,并更新反映在另一个引用中的引用。
您可以使用克隆(深复制)来避免这种情况。
I think both object have same reference.
So
jobsToShiftUp
collection andstate.DestinationAppointmentsSource
might both have some same reference and updating the one reflecting in another.You can use cloning (deep copy) to avoid this .