📜  C#| Boolean.ToString()方法

📅  最后修改于: 2021-05-29 19:44:22             🧑  作者: Mango

此方法用于将该实例的值转换为其等效的字符串表示形式,即“ True ”或“ False ”。

句法:

public override string ToString ();

返回值:该方法返回“真”(在该TrueString财产的价值)如果此实例的值是真实的,还是“假”(即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方法以将其转换为小写。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.boolean.tostring?view=netframework-4.7.2#System_Boolean_ToString