C# Stack 可动态增/删集合对象,其特点是元素后进先出。
Stack<T> StackOfT = new Stack<T>();
例如使用 string 类型堆栈:
// 创建堆栈对象
Stack<string> lstStr = new Stack<string>();
string s1 = "111";
string s2 = "222";
string s3 = "333";
// 将元素压入栈
lstStr.Push(s1);
lstStr.Push(s2);
lstStr.Push(s3);
// 判断元素是否在栈中
if(lstStr.Contains("222"))
{
// 弹出指定元素
string s = lstStr.Pop();
}
// 遍历所有元素
foreach (var item in lstStr)
{
Console.WriteLine(item);
}
// 将堆栈内元素转为数组
object[] objArray = lstStr.ToArray();
// 查看堆栈总大小
int nCount = lstStr.Count();
// 清空堆栈
lstStr.Clear();