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
相關用法
- C# MathF.Abs()用法及代碼示例
- C# MathF.Tan()用法及代碼示例
- C# MathF.Pow()用法及代碼示例
- C# MathF.Sin()用法及代碼示例
- C# MathF.Cos()用法及代碼示例
- C# MathF.Min()用法及代碼示例
- C# MathF.Log()用法及代碼示例
- C# MathF.Exp()用法及代碼示例
- C# MathF.Max()用法及代碼示例
- C# Boolean.GetHashCode()用法及代碼示例
- C# Single.IsFinite()用法及代碼示例
- C# Single.IsNegative()用法及代碼示例
- C# Single.CompareTo()用法及代碼示例
- C# Boolean.GetTypeCode用法及代碼示例
- C# Type.FindInterfaces()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.ToString() Method in C# with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。