任何人都可以解释List<T>
在C#内部的工作原理吗?
public List<ConvData> pdetails = new List<ConvData>();
它是如何存储的?当我们致电pdetails.Add();
答案 0 :(得分:3)
List的实现方式与C ++的向量相同,意味着实现分配预定义大小的数组,填充该数组,当您想要添加元素并且数组已满时,实现分配一个新的数组,更大,将所有值复制到新数组,然后添加新值。 这会导致在添加时AVERAGE性能为O(1),但并非总是如此。
答案 1 :(得分:2)
只需看看at the reference source from Microsoft,看看它是如何运作的。
现在,Add
方法如下所示:
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}
答案 2 :(得分:0)
它是这样开始的:
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items;
[ContractPublicPropertyName("Count")]
private int _size;
注意private T[] _items;
是内部存储列表的方式。
此处.Add(...)
:
public void Add(T item) {
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size++] = item;
_version++;
}