与C#中的示例堆叠
C#中的Stack类表示对象的简单后进先出(LIFO)非通用集合。
以下是Stack类的属性-
Count
GetsthenumberofelementscontainedintheStack.
获取一个值,该值指示对堆栈的访问是否同步(线程安全)。
SyncRoot
Getsanobjectthatcanbeusedtosynchronizeaccess
totheStack.
以下是Stack类的一些方法-
从堆栈中删除所有对象。
Clone()
CreatesashallowcopyoftheStack.
元素是否在堆栈中。
CopyTo(Array,Int32)
CopiestheStacktoanexistingone-dimensionalArray,
startingatthespecifiedarrayindex.
确定指定的对象是否等于当前的对象。
GetEnumerator()
ReturnsanIEnumeratorfortheStack.
用作默认哈希函数。(继承自Object)
GetType()
GetstheTypeofthecurrentinstance.
返回堆栈顶部的对象,但不删除它。
Pop()
RemovesandreturnstheobjectatthetopoftheStack
在堆栈顶部插入一个对象。
示例
现在让我们看一些示例-
为了使对象位于堆栈的顶部,代码如下-
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