ObservableCollection是否维护插入顺序?

jes*_*ess 6 c#

我想知道ObservableCollection是否能保证在C#中维护插入其中的元素的顺序.我查看了MSDN网站但找不到答案.

Ken*_*rey 11

是.

ObservableCollection<T>implements IList<T>,表示项目按您指定的顺序存储.


作为一般规则,这是.NET中基本集合类型的工作方式.

IEnumerable<T> 允许您以未指定的顺序一次访问一个项目.

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

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

  • 请注意他的措辞:“按您指定的顺序”,这意味着如果您使用任何插入方法(而不是“ Add”方法),则最后添加的项不一定在最后一个索引处,尽管仍处于*您指定的*顺序。 (2认同)

Ily*_*nov 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);
}
Run Code Online (Sandbox Code Playgroud)

Collection 在C#中的有序数据结构中,插入和删除后项目的相对顺序不应该改变.


VS1*_*VS1 5

请参阅以下ObservableCollection类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).)
Run Code Online (Sandbox Code Playgroud)

显式接口实现:

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>.)
Run Code Online (Sandbox Code Playgroud)