当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。