ภาพรวม
Stack (non-generic) และ Stack<T> แทนคอลเลกชัน LIFO (Last-In-First-Out) ใช้สำหรับการย้อนกลับ (undo), การประเมินนิพจน์, การค้นหาแบบ depth-first ฯลฯ
คุณสมบัติหลัก
| ลำดับ | คุณสมบัติ | คำอธิบาย |
| 1 | Count | จำนวนสมาชิก |
| 2 | IsSynchronized | thread-safe หรือไม่ |
| 3 | SyncRoot | ออบเจ็กต์สำหรับล็อก |
เมธอดหลัก
| ลำดับ | เมธอด | คำอธิบาย |
| 1 | Clear() | ลบทั้งหมด |
| 2 | Clone() | คัดลอกตื้น (shallow copy) |
| 3 | Contains(Object) | ตรวจสอบว่ามีสมาชิกหรือไม่ |
| 4 | CopyTo(Array, Int32) | คัดลอกไปอาร์เรย์ |
| 5 | Peek() | ดูสมาชิก top โดยไม่ลบ |
| 6 | Pop() | ดึงและลบสมาชิก top |
| 7 | Push(Object) | เพิ่มสมาชิกที่ top |
| 8 | GetEnumerator() | คืน IEnumerator วนลูป |
ตัวอย่างที่ 1: ดูสมาชิก top ด้วย Peek
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
ตัวอย่างที่ 2: ตรวจสอบสมาชิกด้วย 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 element 400? = True
สรุป
- Stack ใช้หลักการ LIFO ตัวสุดท้ายที่ Push จะออกก่อน (Pop)
Peek ดู top โดยไม่ลบ Pop ดูและลบ
- generic
Stack<T> แนะนำกว่า non-generic
- ไม่ได้ thread-safe ใช้
lock(stack.SyncRoot) หรือ ConcurrentStack<T>