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


C# Boolean.ToString()用法及代碼示例

此方法用於將該實例的值轉換為其等效的字符串表示形式,即“True“ 或者 ”False”。

用法:

public override string ToString ();

返回值:如果此實例的值為true,則此方法返回“True”(TrueString屬性的值),如果此實例的值為false,則返回“False”(FalseString屬性的值)。


以下示例程序旨在說明Boolean.ToString()方法的使用:

範例1:

// C# program to demonstrate 
// Boolean.ToString() 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // initalizing the bool variables 
        bool cat = false; 
        bool dog = true; 
  
        // getting the value of string property 
        string value1 = cat.ToString(); 
        string value2 = dog.ToString(); 
  
        // print the string property 
        Console.WriteLine("cat.ToString() returns {0}", value1); 
        Console.WriteLine("dog.ToString() returns {0}", value2); 
    } 
}
輸出:
cat.ToString() returns False
dog.ToString() returns True

範例2:

// C# program to demonstrate 
// Boolean.ToString() 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // initalizing the bool variables 
        bool alpha = false; 
        bool beta = true; 
        bool gama = true; 
        bool delta = false; 
        bool theta = true; 
  
        // calling getValue() method 
        getValue(alpha); 
        getValue(beta); 
        getValue(gama); 
        getValue(delta); 
        getValue(theta); 
    } 
  
    // defining getValue() method 
    public static void getValue(bool variable) 
    { 
  
        // getting the value of string property 
        string value = variable.ToString(); 
  
        // print the string property 
        Console.WriteLine("{0}", value); 
    } 
}
輸出:
False
True
True
False
True

注意:XML區分大小寫,並且XML規範將“true”和“false”識別為有效的布爾值集。如果要將ToString()方法返回的字符串寫入XML文件,則應首先調用其String.ToLowerInvariant方法將其轉換為小寫。

參考:



相關用法


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