C# 中的 Stack 示例

csharpserver side programmingprogramming更新于 2025/9/19 22:37:17

C# 中的 Stack 类表示一个简单的后进先出 (LIFO) 非泛型对象集合。

以下是 Stack 类的属性 −

Sr.No属性 &说明
1Count
获取 Stack 中包含的元素数量。
2IsSynchronized
获取一个值,该值指示对 Stack 的访问是否同步(线程安全)。
3SyncRoot
获取一个可用于同步对 Stack 的访问的对象。

以下是 Stack 类的一些方法 −

Sr.No财产与说明
1Clear()
从 Stack 中移除所有对象。
2Clone()
创建 Stack 的浅表副本。
3Contains(Object)
元素是否在 Stack 中。
4CopyTo(Array, Int32)
从指定的数组索引开始,将 Stack 复制到现有的一维数组。
5Equals(Object)
判断指定对象是否等于当前对象。
6GetEnumerator()
返回 Stack 的 IEnumerator。
7GetHashCode()
用作默认哈希函数。 (从对象继承)
8GetType()
获取当前实例的类型。
9Peek()
返回堆栈顶部的对象而不将其移除。
10Pop()
移除并返回堆栈顶部的对象
11Push(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

相关文章