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


C# Stack.ToString()用法及代码示例


ToString方法是从Object类继承的,该类用于获取表示当前对象的字符串。它也可以应用于堆栈。它返回一个表示当前堆栈对象的字符串。

用法: public virtual string ToString ();

返回值:此方法返回集合的String表示形式。


范例1:在下面的程序中,使用GetType()方法获取当前对象的类型。它将阐明是否将给定的Stack对象转换为字符串。

// C# program to demonstrate 
// Stack ToString() method 
using System; 
using System.Collections; 
  
class GFG { 
  
    public static void Main(String[] args) 
    { 
        // Creating an Empty Stack 
        Stack st = new Stack(); 
  
        // Use Push() method 
        // to add elements to  
        // the stack 
        st.Push("Welcome"); 
        st.Push("To"); 
        st.Push("Geeks"); 
        st.Push("For"); 
        st.Push("Geeks"); 
          
        Console.WriteLine("The type of st before "+ 
                 "ToString Method:"+st.GetType()); 
          
        Console.WriteLine("After ToString Method:"); 
  
        foreach(string str in st) 
        { 
            // Using ToString() method 
            Console.WriteLine(str.ToString()); 
        } 
  
        Console.WriteLine("The type of st after "+ 
            "ToString Method:"+st.ToString().GetType()); 
    } 
}
输出:
The type of st before ToString Method:System.Collections.Stack
After ToString Method:
Geeks
For
Geeks
To
Welcome
The type of st after ToString Method:System.String

范例2:

// C# program to demonstrate 
// Stack ToString() method 
using System; 
using System.Collections; 
  
class GFG { 
  
    public static void Main(String[] args) 
    { 
        // Creating an Empty Stack 
        Stack st = new Stack(); 
  
        // Use Push() method 
        // to add elements to  
        // the stack 
        st.Push(1); 
        st.Push(2); 
        st.Push(3); 
        st.Push(4); 
        st.Push(5); 
          
        Console.WriteLine("The type of st before "+ 
                 "ToString Method:"+st.GetType()); 
          
        Console.WriteLine("After ToString Method:"); 
  
        foreach(int i in st) 
        { 
            // Using ToString() method 
            Console.WriteLine(i.ToString()); 
        } 
  
        Console.WriteLine("The type of st after "+ 
            "ToString Method:"+st.ToString().GetType()); 
    } 
}
输出:
The type of st before ToString Method:System.Collections.Stack
After ToString Method:
5
4
3
2
1
The type of st after ToString Method:System.String


相关用法


注:本文由纯净天空筛选整理自Kirti_Mangal大神的英文原创作品 Stack.ToString() Method in C# with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。