Stack内部通过数组来实现数据的存储,其大部分方法和List相同,这里不再分析,有兴趣的请自行查看源码。Stack通过字段_size来表示内部存储的元素数量,由于Stack时先进后出,所以通过_size控制内部数组的最后一个元素的添加和删除即可。
Peek函数:
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Peek"]/*' />
public T Peek() {
if (_size==0)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);
return _array[_size-1];
}
可以看到,当_size(存储的元素数量)为0时(即为空栈)时,会抛出异常;返回最后一个元素 _array[_size-1]。
Pop函数:
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Pop"]/*' />
public T Pop() {
if (_size == 0)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);
_version++;
T item = _array[--_size];
_array[_size] = default(T); // Free memory quicker.
return item;
}
和Peek函数相似,置空数组的最后一个元素,并弹出,同时更新元素数量。
Push函数:
// Pushes an item to the top of the stack.
//
/// <include file='doc\Stack.uex' path='docs/doc[@for="Stack.Push"]/*' />
public void Push(T item) {
if (_size == _array.Length) {
T[] newArray = new T[(_array.Length == 0) ? _defaultCapacity : 2*_array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = item;
_version++;
}
Push函数会首先判断一下内部数组是否已满,若满,则扩容2倍。
源码为.net 4.5.1;
.net源码网址:https://referencesource.microsoft.com/
注:本人水平有限,如果有错误,欢迎指正……