ObservableCollection是否保持插入顺序?

6
我想知道在C#中,ObservableCollection是否保证插入元素的顺序。我查看了MSDN网站,但找不到答案。
3个回答

11

是的。

ObservableCollection<T> 实现了 IList<T>,这意味着项目按您指定的顺序存储。


作为.NET中基本集合类型的一般规则。

IEnumerable<T> 允许您以未指定的顺序逐个访问项目。

ICollection<T> 除了具有 IEnumerable<T> 的功能外,还允许您添加和删除项目并访问集合的总大小。

IList<T> 除了具有 ICollection<T> 的功能外,还允许您通过索引访问项目,并在任意索引处插入和删除项目。


3
请注意他的措辞:“按照您指定的顺序”,这意味着如果您使用任何插入方法(而不是Add方法),则最后添加的项可能不一定位于最后一个索引,但仍按照 您指定的 顺序排序。 - tnw

5

它派生自Collection<T>,使用IList<T> items存储数据。在添加和删除项目时,ObservableCollection只是将调用委托给基类。

protected override void InsertItem(int index, T item)
{
  this.CheckReentrancy();
  base.InsertItem(index, item);
  this.OnPropertyChanged("Count");
  this.OnPropertyChanged("Item[]");
  this.OnCollectionChanged(NotifyCollectionChangedAction.Add, (object) item, index);
}

Collection在C#中是一种有序数据结构,因此插入和删除项目后的相对顺序不应更改。


5

请看下面摘自 ObservableCollection Class MSDN 文档的节选:

方法:

Add         Adds an object to the *end* of the Collection<T>. (Inherited from Collection<T>.)

Insert      Inserts an element into the Collection<T> at the *specified index*. (Inherited from Collection<T>.)

InsertItem  Inserts an item into the collection at the *specified index*. (Overrides Collection<T>.InsertItem(Int32, T).)

显式接口实现:

IList.Add      Adds an item to the IList. (Inherited from Collection<T>.)

IList.Insert   Inserts an item into the IList at the specified index. (Inherited from Collection<T>.)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接