在以下方法中,当我将IEnumerable
结果复制到带有 的列表时ToList()
,不会在的构造函数中调用终结器,并且视图模型仅在程序关闭时才最终确定:ObservableCollection
IList
IDisposable
private void ReadHeaders()
{
IList<PlanningGridHeaderVM> viewModelSet =
(from header in _planningGridService.ReloadHeaders().OrderBy(x => x.PlanNumber)
select new PlanningGridHeaderVM((PlanningGridHeader)header)).ToList();
foreach (PlanningGridHeaderVM headerVM in viewModelSet)
{
ItemEditedEventManager.AddHandler(headerVM, OnItemEdited);
PropertyChangedEventManager.AddHandler(headerVM, OnPropertyChanged, string.Empty);
}
this.ViewModels = new ObservableCollection<PlanningGridHeaderVM>(viewModelSet);
CollectionChangedEventManager.AddHandler(this.ViewModels, this.OnCollectionChanged);
}
然而,当我IEnumerable
直接在ObservableCollection
's 的IEnumerable
构造函数中使用结果时,我的 Debug 输出通知我所有IDisposable
视图模型项都由GC 完成(这让我感到困惑)。
尽管如此,我仍然在屏幕上获得了所需的集合,并且在程序关闭后,它们都再次完成(这一次,正如预期的那样):
private void ReadHeaders()
{
IEnumerable<PlanningGridHeaderVM> viewModelSet =
(from header in _planningGridService.ReloadHeaders().OrderBy(x => x.PlanNumber)
select new PlanningGridHeaderVM((PlanningGridHeader)header));
foreach (PlanningGridHeaderVM headerVM in viewModelSet)
{
ItemEditedEventManager.AddHandler(headerVM, OnItemEdited);
PropertyChangedEventManager.AddHandler(headerVM, OnPropertyChanged, string.Empty);
}
this.ViewModels = new ObservableCollection<PlanningGridHeaderVM>(viewModelSet);
CollectionChangedEventManager.AddHandler(this.ViewModels, this.OnCollectionChanged);
}
为什么?两者的 MSDN 页面(这里和这里)都说“元素被复制到 ObservableCollection 上的顺序与集合的枚举器读取它们的顺序相同。”