有人请说明如何实现Add方法
(如何在c#中为List实现Add方法)
listobject.Add(); List<User> listobject= new List<User>()对象的声明在哪里.
我知道使用List我们可以快速执行许多操作,而且类型安全也是如此,但我想知道如何实现id add方法,以便在运行时处理所有这些.
希望它不会复制对象并在每次添加时进行调整,但我会保持手指交叉并等待您的回复:)
使用Reflector,您可以准确地看到它的实现方式.
public void Add(T item)
{
if (this._size == this._items.Length)
{
this.EnsureCapacity(this._size + 1);
}
this._items[this._size++] = item;
this._version++;
}
Run Code Online (Sandbox Code Playgroud)
关注'EnsureCapacity'......
private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
Run Code Online (Sandbox Code Playgroud)
最后是'容量'的制定者
public int Capacity
{
get
{
return this._items.Length;
}
set
{
if (value != this._items.Length)
{
if (value < this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
if (value > 0)
{
T[] destinationArray = new T[value];
if (this._size > 0)
{
Array.Copy(this._items, 0, destinationArray, 0, this._size);
}
this._items = destinationArray;
}
else
{
this._items = List<T>._emptyArray;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |