C#中的Stack类表示对象的简单后进先出(LIFO)非通用集合。
以下是Stack类的属性-
| 序号 | 属性和说明 |
|---|---|
| 1个 | Count |
| 2 | IsSynchronized 获取一个值,该值指示对堆栈的访问是否同步(线程安全)。 |
| 3 | SyncRoot |
以下是Stack类的一些方法-
| 序号 | 属性和说明 |
|---|---|
| 1个 | Clear() 从堆栈中删除所有对象。 |
| 2 | Clone() |
| 3 | 包含(Object) 元素是否在堆栈中。 |
| 4 | CopyTo(Array, Int32) |
| 5 | Equals(Object) 确定指定的对象是否等于当前的对象。 |
| 6 | GetEnumerator() |
| 7 | GetHashCode() 用作默认哈希函数。(继承自Object) |
| 8 | GetType() |
| 9 | Peek() 返回堆栈顶部的对象,但不删除它。 |
| 10 | Pop() |
| 11 | Push(Object) 在堆栈顶部插入一个对象。 |
现在让我们看一些示例-
为了使对象位于堆栈的顶部,代码如下-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<string> stack = new Stack<string>();
stack.Push("A");
stack.Push("B");
stack.Push("C");
stack.Push("D");
stack.Push("E");
stack.Push("F");
stack.Push("G");
stack.Push("H");
stack.Push("I");
stack.Push("J");
Console.WriteLine("Count of elements = "+stack.Count);
Console.WriteLine("Element at the top of stack = " + stack.Peek());
}
}输出结果
这将产生以下输出-
Count of elements = 10 Element at the top of stack = J Count of elements = 10
若要检查Stack是否具有元素,请使用C#Contains()方法。以下是代码-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
Stack<int> stack = new Stack<int>();
stack.Push(100);
stack.Push(150);
stack.Push(175);
stack.Push(200);
stack.Push(225);
stack.Push(250);
stack.Push(300);
stack.Push(400);
stack.Push(450);
stack.Push(500);
Console.WriteLine("Elements in the Stack:");
foreach(var val in stack) {
Console.WriteLine(val);
}
Console.WriteLine("Count of elements in the Stack = "+stack.Count);
Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
}
}输出结果
这将产生以下输出-
Elements in the Stack: 500 450 400 300 250 225 200 175 150 100 Count of elements in the Stack = 10 Does Stack has the element40400?= False