bool (C# 參考)

更新:2007 年 11 月

bool 關鍵字是 System.Boolean 的別名。它是用來宣告儲存布林值 truefalse 的變數。

注意事項:

如果您需要可以同時具有 null 值的布林值變數,請使用 bool?。如需詳細資訊,請參閱可為 Null 的型別 (C# 程式設計手冊)

常值

您可以將布林值指派給 bool 變數。您也可以將評估為 bool 的運算式指派給 bool 變數。

public class BoolTest
{
    static void Main()
    {
        bool b = true;

        // WriteLine automatically converts the value of b to text.
        Console.WriteLine(b);

        int days = DateTime.Now.DayOfYear;


        // Assign the result of a boolean expression to b.
        b = (days % 2 == 0);

        if (true == b)
        {
            Console.WriteLine("days is an even number");
        }
        else
        {
            Console.WriteLine("days is an odd number");
        }   
    }
}
/* Output:
  True
  days is an <even/odd> number
*/

轉換

在 C++ 裡,bool 型別的值可以轉換成 int 型別的值;換句話說,false 等於零,而 true 則等於非零值。在 C# 中,bool 型別和其他型別之間不能轉換。例如,在 C# 中,下列 if 陳述式是無效的:

int x = 123;

// if (x)   // Error: "Cannot implicitly convert type 'int' to 'bool'"
{
    Console.Write("The value of x is nonzero.");
}

若要測試 int 型別的變數,您必須將該變數與另一個值 (例如零) 明確地做比較,如下所示:

if (x != 0)   // The C# way
{
    Console.Write("The value of x is nonzero.");
}

範例

在這個範例中,由鍵盤輸入一個字元後,程式會檢查輸入的字元是否為字母。如果是字母,將檢查是大寫或小寫。這些檢查是使用 IsLetterIsLower 來執行,這兩者都會傳回 bool 型別:

public class BoolKeyTest
{
    static void Main()
    {
        Console.Write("Enter a character: ");
        char c = (char)Console.Read();
        if (Char.IsLetter(c))
        {
            if (Char.IsLower(c))
            {
                Console.WriteLine("The character is lowercase.");
            }
            else
            {
                Console.WriteLine("The character is uppercase.");
            }
        }
        else
        {
            Console.WriteLine("Not an alphabetic character.");
        }
    }
}
/* Sample Output:
    Enter a character: X
    The character is uppercase.

    Enter a character: x
    The character is lowercase.

    Enter a character: 2
    The character is not an alphabetic character.
 */

C# 語言規格

如需 bool 和相關物件的詳細資訊,請參閱 C# 語言規格中的下列章節:

  • 4.1.8 bool 型別

  • 7.9.4 布林值等號比較運算子

  • 7.11.1 布林值條件邏輯運算子

請參閱

概念

C# 程式設計手冊

參考

C# 關鍵字

整數類資料型別表 (C# 參考)

內建型別資料表 (C# 參考)

隱含數值轉換表 (C# 參考)

明確數值轉換表 (C# 參考)

其他資源

C# 參考