當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Stack.Peek用法及代碼示例

此方法(位於System.Collections命名空間下)用於在不刪除對象的情況下返回堆棧頂部的對象。此方法類似於Pop方法,但是Peek不會修改Stack。

用法:

public virtual object Peek ();

返回值:它返回堆棧頂部的對象。


異常:在空堆棧上調用Peek()方法將引發InvalidOperationException。因此,在使用Peek()方法檢索元素之前,請始終檢查堆棧中的元素。

下麵給出了一些示例,以更好地理解實現。

示例1:

// C# code to illustrate the 
// Stack.Peek Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Inserting the elements into the Stack 
        myStack.Push("1st Element"); 
        myStack.Push("2nd Element"); 
        myStack.Push("3rd Element"); 
        myStack.Push("4th Element"); 
        myStack.Push("5th Element"); 
        myStack.Push("6th Element"); 
  
        // Displaying the count of elements 
        // contained in the Stack 
        Console.Write("Total number of elements"+ 
                         " in the Stack are : "); 
  
        Console.WriteLine(myStack.Count); 
  
        // Displaying the top element of Stack 
        // without removing it from the Stack 
        Console.WriteLine("Element at the top is : " 
                                  + myStack.Peek()); 
  
        // Displaying the top element of Stack 
        // without removing it from the Stack 
        Console.WriteLine("Element at the top is : " 
                                + myStack.Peek()); 
  
        // Displaying the count of elements 
        // contained in the Stack 
        Console.Write("Total number of elements "+ 
                           "in the Stack are : "); 
  
        Console.WriteLine(myStack.Count); 
    } 
}

輸出:

Total number of elements in the Stack are : 6
Element at the top is : 6th Element
Element at the top is : 6th Element
Total number of elements in the Stack are : 6

示例2:

// C# code to illustrate the 
// Stack.Peek Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Displaying the top element of Stack 
        // without removing it from the Stack 
        // Calling Peek() method on empty stack 
        // will throw InvalidOperationException. 
        Console.WriteLine("Element at the top is : " 
                               + myStack.Peek()); 
    } 
}

運行時錯誤:

Unhandled Exception:
System.InvalidOperationException: Stack empty.

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Peek Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。