bool (c # 參考) bool (C# reference)

boolType 關鍵字是 System.Boolean 代表布林值(可以是或)之 .net 結構類型的別名 true falseThe bool type keyword is an alias for the .NET System.Boolean structure type that represents a Boolean value, which can be either true or false.

若要執行具有類型值的邏輯作業 bool ,請使用 布林值邏輯 運算子。To perform logical operations with values of the bool type, use Boolean logical operators. bool 類型是比較和等號比較運算子的結果型別。The bool type is the result type of comparison and equality operators. bool運算式可以是ifdowhilefor語句和條件運算子 ?: 中的控制條件運算式。A bool expression can be a controlling conditional expression in the if, do, while, and for statements and in the conditional operator ?:.

此類型的預設值 boolfalseThe default value of the bool type is false.

常值Literals

您可以使用 truefalse 常值來初始化 bool 變數或傳遞 bool 值:You can use the true and false literals to initialize a bool variable or to pass a bool value:

bool check = true;
Console.WriteLine(check ? "Checked" : "Not checked");  // output: Checked

Console.WriteLine(false ? "Checked" : "Not checked");  // output: Not checked

三值布林值邏輯Three-valued Boolean logic

bool?如果您需要支援三值的邏輯(例如,當您使用支援三值布林類型的資料庫時),請使用可為 null 的型別。Use the nullable bool? type, if you need to support the three-valued logic, for example, when you work with databases that support a three-valued Boolean type. 針對 bool? 運算元,預先定義的 &| 運算子支援三值邏輯。For the bool? operands, the predefined & and | operators support the three-valued logic. 如需詳細資訊,請參閱布林邏輯運算子一文的可為 Null 的布林邏輯運算子一節。For more information, see the Nullable Boolean logical operators section of the Boolean logical operators article.

如需可為 null 實值型別的詳細資訊,請參閱可為 null 的實數值型別For more information about nullable value types, see Nullable value types.

轉換Conversions

C # 只會提供兩個牽涉到類型的轉換 boolC# provides only two conversions that involve the bool type. 這些是對應至可為 null 之型別的隱含轉換 bool? ,以及來自型別的明確轉換 bool?Those are an implicit conversion to the corresponding nullable bool? type and an explicit conversion from the bool? type. 不過,.NET 提供其他方法,可讓您用來在類型之間進行轉換 boolHowever, .NET provides additional methods that you can use to convert to or from the bool type. 如需詳細資訊,請參閱 API 參考頁面的 轉換為和來源布林值 一節 System.BooleanFor more information, see the Converting to and from Boolean values section of the System.Boolean API reference page.

C# 語言規格C# language specification

如需詳細資訊,請參閱c # 語言規格bool 類型一節。For more information, see The bool type section of the C# language specification.

另請參閱See also