System.Boolean 結構
本文提供此 API 參考文件的補充備註。
Boolean實體可以有兩個值之一:true
或 false
。
結構 Boolean 提供支援下列工作的方法:
本文說明這些工作和其他使用方式詳細數據。
格式化布爾值
的Boolean字串表示法是true
值的 「True」 或值的 「False」。。false
值的字串表示 Boolean 是由唯讀 TrueString 和 FalseString 欄位所定義。
您可以使用 ToString 方法將布林值轉換成字串。 布爾結構包含兩 ToString 個多載:無 ToString() 參數方法和 ToString(IFormatProvider) 方法,其中包含可控制格式設定的參數。 不過,由於忽略此參數,這兩個多載會產生相同的字串。 ToString(IFormatProvider)方法不支援區分文化特性的格式。
下列範例說明使用 方法的格式 ToString 設定。 請注意,C# 和 VB 範例使用 複合格式 設定功能,而 F# 範例則使用 字串插補。 在這兩種情況下, ToString 都會隱含呼叫 方法。
using System;
public class Example10
{
public static void Main()
{
bool raining = false;
bool busLate = true;
Console.WriteLine("It is raining: {0}", raining);
Console.WriteLine("The bus is late: {0}", busLate);
}
}
// The example displays the following output:
// It is raining: False
// The bus is late: True
let raining = false
let busLate = true
printfn $"It is raining: {raining}"
printfn $"The bus is late: {busLate}"
// The example displays the following output:
// It is raining: False
// The bus is late: True
Module Example9
Public Sub Main()
Dim raining As Boolean = False
Dim busLate As Boolean = True
Console.WriteLine("It is raining: {0}", raining)
Console.WriteLine("The bus is late: {0}", busLate)
End Sub
End Module
' The example displays the following output:
' It is raining: False
' The bus is late: True
因為結構 Boolean 只能有兩個值,所以很容易新增自定義格式設定。 對於其他字串常值取代為 「True」 和 「False」 的簡單自定義格式,您可以使用語言所支援的任何條件式評估功能,例如 C# 中的條件運算子或 Visual Basic 中的 If 運算符。 下列範例會使用這項技術將值格式化 Boolean 為 「Yes」 和 「No」,而不是 「True」 和 「False」。
using System;
public class Example11
{
public static void Main()
{
bool raining = false;
bool busLate = true;
Console.WriteLine("It is raining: {0}",
raining ? "Yes" : "No");
Console.WriteLine("The bus is late: {0}",
busLate ? "Yes" : "No");
}
}
// The example displays the following output:
// It is raining: No
// The bus is late: Yes
Module Example
Public Sub Main()
Dim raining As Boolean = False
Dim busLate As Boolean = True
Console.WriteLine("It is raining: {0}",
If(raining, "Yes", "No"))
Console.WriteLine("The bus is late: {0}",
If(busLate, "Yes", "No"))
End Sub
End Module
' The example displays the following output:
' It is raining: No
' The bus is late: Yes
let raining = false
let busLate = true
printfn $"""It is raining: %s{if raining then "Yes" else "No"}"""
printfn $"""The bus is late: %s{if busLate then "Yes" else "No"}"""
// The example displays the following output:
// It is raining: No
// The bus is late: Yes
如需更複雜的自定義格式設定作業,包括區分文化特性的格式設定,您可以呼叫 String.Format(IFormatProvider, String, Object[]) 方法並提供實 ICustomFormatter 作。 下列範例會實作 ICustomFormatter 和 IFormatProvider 介面,為英文(美國)、法文(法國)和俄羅斯(俄羅斯)文化特性提供區分文化特性的布爾字串。
using System;
using System.Globalization;
public class Example4
{
public static void Main()
{
String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" };
foreach (var cultureName in cultureNames) {
bool value = true;
CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
BooleanFormatter formatter = new BooleanFormatter(culture);
string result = string.Format(formatter, "Value for '{0}': {1}", culture.Name, value);
Console.WriteLine(result);
}
}
}
public class BooleanFormatter : ICustomFormatter, IFormatProvider
{
private CultureInfo culture;
public BooleanFormatter() : this(CultureInfo.CurrentCulture)
{ }
public BooleanFormatter(CultureInfo culture)
{
this.culture = culture;
}
public Object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
else
return null;
}
public string Format(string fmt, Object arg, IFormatProvider formatProvider)
{
// Exit if another format provider is used.
if (! formatProvider.Equals(this)) return null;
// Exit if the type to be formatted is not a Boolean
if (! (arg is Boolean)) return null;
bool value = (bool) arg;
switch (culture.Name) {
case "en-US":
return value.ToString();
case "fr-FR":
if (value)
return "vrai";
else
return "faux";
case "ru-RU":
if (value)
return "верно";
else
return "неверно";
default:
return value.ToString();
}
}
}
// The example displays the following output:
// Value for '': True
// Value for 'en-US': True
// Value for 'fr-FR': vrai
// Value for 'ru-RU': верно
open System
open System.Globalization
type BooleanFormatter(culture) =
interface ICustomFormatter with
member this.Format(_, arg, formatProvider) =
if formatProvider <> this then null
else
match arg with
| :? bool as value ->
match culture.Name with
| "en-US" -> string arg
| "fr-FR" when value -> "vrai"
| "fr-FR" -> "faux"
| "ru-RU" when value -> "верно"
| "ru-RU" -> "неверно"
| _ -> string arg
| _ -> null
interface IFormatProvider with
member this.GetFormat(formatType) =
if formatType = typeof<ICustomFormatter> then this
else null
new() = BooleanFormatter CultureInfo.CurrentCulture
let cultureNames = [ ""; "en-US"; "fr-FR"; "ru-RU" ]
for cultureName in cultureNames do
let value = true
let culture = CultureInfo.CreateSpecificCulture cultureName
let formatter = BooleanFormatter culture
String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
|> printfn "%s"
// The example displays the following output:
// Value for '': True
// Value for 'en-US': True
// Value for 'fr-FR': vrai
// Value for 'ru-RU': верно
Imports System.Globalization
Module Example4
Public Sub Main()
Dim cultureNames() As String = {"", "en-US", "fr-FR", "ru-RU"}
For Each cultureName In cultureNames
Dim value As Boolean = True
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
Dim formatter As New BooleanFormatter(culture)
Dim result As String = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
Console.WriteLine(result)
Next
End Sub
End Module
Public Class BooleanFormatter
Implements ICustomFormatter, IFormatProvider
Private culture As CultureInfo
Public Sub New()
Me.New(CultureInfo.CurrentCulture)
End Sub
Public Sub New(culture As CultureInfo)
Me.culture = culture
End Sub
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, arg As Object,
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
' Exit if another format provider is used.
If Not formatProvider.Equals(Me) Then Return Nothing
' Exit if the type to be formatted is not a Boolean
If Not TypeOf arg Is Boolean Then Return Nothing
Dim value As Boolean = CBool(arg)
Select culture.Name
Case "en-US"
Return value.ToString()
Case "fr-FR"
If value Then
Return "vrai"
Else
Return "faux"
End If
Case "ru-RU"
If value Then
Return "верно"
Else
Return "неверно"
End If
Case Else
Return value.ToString()
End Select
End Function
End Class
' The example displays the following output:
' Value for '': True
' Value for 'en-US': True
' Value for 'fr-FR': vrai
' Value for 'ru-RU': верно
您可以選擇性地使用 資源檔案 來定義特定文化特性的布林字串。
從布爾值來回轉換
結構 Boolean 會實作 IConvertible 介面。 因此,您可以使用 Convert 類別,在 .NET 中執行值與任何其他基本類型之間的 Boolean 轉換,也可以呼叫 Boolean 結構的明確實作。 不過,不支援 與下列類型之間的 Boolean 轉換,因此對應的轉換方法會擲回 InvalidCastException 例外狀況:
和 Char 之間的Boolean轉換(Convert.ToBoolean(Char)和 Convert.ToChar(Boolean) 方法)。
和 DateTime 之間的Boolean轉換(Convert.ToBoolean(DateTime)和 Convert.ToDateTime(Boolean) 方法)。
從整數或浮點數到布林值的所有轉換,會將非零值 true
轉換成 ,並將零值轉換成 false
。 下列範例會藉由呼叫 類別的 Convert.ToBoolean 選取多載來說明這一點。
using System;
public class Example2
{
public static void Main()
{
Byte byteValue = 12;
Console.WriteLine(Convert.ToBoolean(byteValue));
Byte byteValue2 = 0;
Console.WriteLine(Convert.ToBoolean(byteValue2));
int intValue = -16345;
Console.WriteLine(Convert.ToBoolean(intValue));
long longValue = 945;
Console.WriteLine(Convert.ToBoolean(longValue));
SByte sbyteValue = -12;
Console.WriteLine(Convert.ToBoolean(sbyteValue));
double dblValue = 0;
Console.WriteLine(Convert.ToBoolean(dblValue));
float sngValue = .0001f;
Console.WriteLine(Convert.ToBoolean(sngValue));
}
}
// The example displays the following output:
// True
// False
// True
// True
// True
// False
// True
open System
let byteValue = 12uy
printfn $"{Convert.ToBoolean byteValue}"
let byteValue2 = 0uy
printfn $"{Convert.ToBoolean byteValue2}"
let intValue = -16345
printfn $"{Convert.ToBoolean intValue}"
let longValue = 945L
printfn $"{Convert.ToBoolean longValue}"
let sbyteValue = -12y
printfn $"{Convert.ToBoolean sbyteValue}"
let dblValue = 0.0
printfn $"{Convert.ToBoolean dblValue}"
let sngValue = 0.0001f
printfn $"{Convert.ToBoolean sngValue}"
// The example displays the following output:
// True
// False
// True
// True
// True
// False
// True
Module Example2
Public Sub Main()
Dim byteValue As Byte = 12
Console.WriteLine(Convert.ToBoolean(byteValue))
Dim byteValue2 As Byte = 0
Console.WriteLine(Convert.ToBoolean(byteValue2))
Dim intValue As Integer = -16345
Console.WriteLine(Convert.ToBoolean(intValue))
Dim longValue As Long = 945
Console.WriteLine(Convert.ToBoolean(longValue))
Dim sbyteValue As SByte = -12
Console.WriteLine(Convert.ToBoolean(sbyteValue))
Dim dblValue As Double = 0
Console.WriteLine(Convert.ToBoolean(dblValue))
Dim sngValue As Single = 0.0001
Console.WriteLine(Convert.ToBoolean(sngValue))
End Sub
End Module
' The example displays the following output:
' True
' False
' True
' True
' True
' False
' True
從布爾值轉換成數值時,類別的 Convert 轉換方法會轉換成 true
1和 false
0。 不過,Visual Basic 轉換函式會轉換成 true
255(用於值轉換 Byte )或 -1(所有其他數值轉換)。 下列範例會使用 Convert 方法轉換成true
數值,在Visual Basic範例的案例中,使用Visual Basic語言自己的轉換運算符。
using System;
public class Example3
{
public static void Main()
{
bool flag = true;
byte byteValue;
byteValue = Convert.ToByte(flag);
Console.WriteLine("{0} -> {1}", flag, byteValue);
sbyte sbyteValue;
sbyteValue = Convert.ToSByte(flag);
Console.WriteLine("{0} -> {1}", flag, sbyteValue);
double dblValue;
dblValue = Convert.ToDouble(flag);
Console.WriteLine("{0} -> {1}", flag, dblValue);
int intValue;
intValue = Convert.ToInt32(flag);
Console.WriteLine("{0} -> {1}", flag, intValue);
}
}
// The example displays the following output:
// True -> 1
// True -> 1
// True -> 1
// True -> 1
open System
let flag = true
let byteValue = Convert.ToByte flag
printfn $"{flag} -> {byteValue}"
let sbyteValue = Convert.ToSByte flag
printfn $"{flag} -> {sbyteValue}"
let dblValue = Convert.ToDouble flag
printfn $"{flag} -> {dblValue}"
let intValue = Convert.ToInt32(flag);
printfn $"{flag} -> {intValue}"
// The example displays the following output:
// True -> 1
// True -> 1
// True -> 1
// True -> 1
Module Example3
Public Sub Main()
Dim flag As Boolean = True
Dim byteValue As Byte
byteValue = Convert.ToByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, byteValue,
byteValue.GetType().Name)
byteValue = CByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, byteValue,
byteValue.GetType().Name)
Dim sbyteValue As SByte
sbyteValue = Convert.ToSByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue,
sbyteValue.GetType().Name)
sbyteValue = CSByte(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, sbyteValue,
sbyteValue.GetType().Name)
Dim dblValue As Double
dblValue = Convert.ToDouble(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, dblValue,
dblValue.GetType().Name)
dblValue = CDbl(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, dblValue,
dblValue.GetType().Name)
Dim intValue As Integer
intValue = Convert.ToInt32(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, intValue,
intValue.GetType().Name)
intValue = CInt(flag)
Console.WriteLine("{0} -> {1} ({2})", flag, intValue,
intValue.GetType().Name)
End Sub
End Module
' The example displays the following output:
' True -> 1 (Byte)
' True -> 255 (Byte)
' True -> 1 (SByte)
' True -> -1 (SByte)
' True -> 1 (Double)
' True -> -1 (Double)
' True -> 1 (Int32)
' True -> -1 (Int32)
如需從 Boolean 轉換為字串值的轉換,請參閱 格式化布爾值 一節。 如需從字串轉換成 Boolean 值,請參閱 剖析布爾值 一節。
剖析布爾值
結構 Boolean 包含兩個靜態剖析方法, Parse 以及 TryParse,可將字串轉換成布爾值。 布爾值的字串表示是由和 字段的值不區分大小寫的對等專案所定義,這些值TrueStringFalseString分別是 “True” 和 “False”。 換句話說,剖析成功的唯一字串是 「True」、“False”、“true”、“false” 或某些混合大小寫對等專案。 您無法成功剖析數值字串,例如 「0」 或 「1」。 執行字串比較時,不會考慮前置或尾端空格符。
下列範例會使用 Parse 和 TryParse 方法來剖析一些字串。 請注意,只有不區分大小寫的 「True」 和 「False」 對等專案可以成功剖析。
using System;
public class Example7
{
public static void Main()
{
string[] values = { null, String.Empty, "True", "False",
"true", "false", " true ",
"TrUe", "fAlSe", "fa lse", "0",
"1", "-1", "string" };
// Parse strings using the Boolean.Parse method.
foreach (var value in values) {
try {
bool flag = Boolean.Parse(value);
Console.WriteLine("'{0}' --> {1}", value, flag);
}
catch (ArgumentException) {
Console.WriteLine("Cannot parse a null string.");
}
catch (FormatException) {
Console.WriteLine("Cannot parse '{0}'.", value);
}
}
Console.WriteLine();
// Parse strings using the Boolean.TryParse method.
foreach (var value in values) {
bool flag = false;
if (Boolean.TryParse(value, out flag))
Console.WriteLine("'{0}' --> {1}", value, flag);
else
Console.WriteLine("Unable to parse '{0}'", value);
}
}
}
// The example displays the following output:
// Cannot parse a null string.
// Cannot parse ''.
// 'True' --> True
// 'False' --> False
// 'true' --> True
// 'false' --> False
// ' true ' --> True
// 'TrUe' --> True
// 'fAlSe' --> False
// Cannot parse 'fa lse'.
// Cannot parse '0'.
// Cannot parse '1'.
// Cannot parse '-1'.
// Cannot parse 'string'.
//
// Unable to parse ''
// Unable to parse ''
// 'True' --> True
// 'False' --> False
// 'true' --> True
// 'false' --> False
// ' true ' --> True
// 'TrUe' --> True
// 'fAlSe' --> False
// Cannot parse 'fa lse'.
// Unable to parse '0'
// Unable to parse '1'
// Unable to parse '-1'
// Unable to parse 'string'
open System
let values =
[ null; String.Empty; "True"; "False"
"true"; "false"; " true "
"TrUe"; "fAlSe"; "fa lse"; "0"
"1"; "-1"; "string" ]
// Parse strings using the Boolean.Parse method.
for value in values do
try
let flag = Boolean.Parse value
printfn $"'{value}' --> {flag}"
with
| :? ArgumentException ->
printfn "Cannot parse a null string."
| :? FormatException ->
printfn $"Cannot parse '{value}'."
printfn ""
// Parse strings using the Boolean.TryParse method.
for value in values do
match Boolean.TryParse value with
| true, flag ->
printfn $"'{value}' --> {flag}"
| false, _ ->
printfn $"Unable to parse '{value}'"
// The example displays the following output:
// Cannot parse a null string.
// Cannot parse ''.
// 'True' --> True
// 'False' --> False
// 'true' --> True
// 'false' --> False
// ' true ' --> True
// 'TrUe' --> True
// 'fAlSe' --> False
// Cannot parse 'fa lse'.
// Cannot parse '0'.
// Cannot parse '1'.
// Cannot parse '-1'.
// Cannot parse 'string'.
//
// Unable to parse ''
// Unable to parse ''
// 'True' --> True
// 'False' --> False
// 'true' --> True
// 'false' --> False
// ' true ' --> True
// 'TrUe' --> True
// 'fAlSe' --> False
// Cannot parse 'fa lse'.
// Unable to parse '0'
// Unable to parse '1'
// Unable to parse '-1'
// Unable to parse 'string'
Module Example7
Public Sub Main()
Dim values() As String = {Nothing, String.Empty, "True", "False",
"true", "false", " true ",
"TrUe", "fAlSe", "fa lse", "0",
"1", "-1", "string"}
' Parse strings using the Boolean.Parse method.
For Each value In values
Try
Dim flag As Boolean = Boolean.Parse(value)
Console.WriteLine("'{0}' --> {1}", value, flag)
Catch e As ArgumentException
Console.WriteLine("Cannot parse a null string.")
Catch e As FormatException
Console.WriteLine("Cannot parse '{0}'.", value)
End Try
Next
Console.WriteLine()
' Parse strings using the Boolean.TryParse method.
For Each value In values
Dim flag As Boolean = False
If Boolean.TryParse(value, flag) Then
Console.WriteLine("'{0}' --> {1}", value, flag)
Else
Console.WriteLine("Cannot parse '{0}'.", value)
End If
Next
End Sub
End Module
' The example displays the following output:
' Cannot parse a null string.
' Cannot parse ''.
' 'True' --> True
' 'False' --> False
' 'true' --> True
' 'false' --> False
' ' true ' --> True
' 'TrUe' --> True
' 'fAlSe' --> False
' Cannot parse 'fa lse'.
' Cannot parse '0'.
' Cannot parse '1'.
' Cannot parse '-1'.
' Cannot parse 'string'.
'
' Unable to parse ''
' Unable to parse ''
' 'True' --> True
' 'False' --> False
' 'true' --> True
' 'false' --> False
' ' true ' --> True
' 'TrUe' --> True
' 'fAlSe' --> False
' Cannot parse 'fa lse'.
' Unable to parse '0'
' Unable to parse '1'
' Unable to parse '-1'
' Unable to parse 'string'
如果您是在 Visual Basic 中進行程式設計,您可以使用 函 CBool
式將數位的字串表示轉換成布爾值。 “0” 會轉換成 false
,且任何非零值的字串表示會 true
轉換成 。 如果您不是在 Visual Basic 中進行程式設計,您必須先將數值字串轉換成數位,才能將它轉換成布爾值。 下列範例會藉由將整數數位轉換成布爾值來說明這一點。
using System;
public class Example8
{
public static void Main()
{
String[] values = { "09", "12.6", "0", "-13 " };
foreach (var value in values) {
bool success, result;
int number;
success = Int32.TryParse(value, out number);
if (success) {
// The method throws no exceptions.
result = Convert.ToBoolean(number);
Console.WriteLine("Converted '{0}' to {1}", value, result);
}
else {
Console.WriteLine("Unable to convert '{0}'", value);
}
}
}
}
// The example displays the following output:
// Converted '09' to True
// Unable to convert '12.6'
// Converted '0' to False
// Converted '-13 ' to True
open System
let values = [ "09"; "12.6"; "0"; "-13 " ]
for value in values do
match Int32.TryParse value with
| true, number ->
// The method throws no exceptions.
let result = Convert.ToBoolean number
printfn $"Converted '{value}' to {result}"
| false, _ ->
printfn $"Unable to convert '{value}'"
// The example displays the following output:
// Converted '09' to True
// Unable to convert '12.6'
// Converted '0' to False
// Converted '-13 ' to True
Module Example8
Public Sub Main()
Dim values() As String = {"09", "12.6", "0", "-13 "}
For Each value In values
Dim success, result As Boolean
Dim number As Integer
success = Int32.TryParse(value, number)
If success Then
' The method throws no exceptions.
result = Convert.ToBoolean(number)
Console.WriteLine("Converted '{0}' to {1}", value, result)
Else
Console.WriteLine("Unable to convert '{0}'", value)
End If
Next
End Sub
End Module
' The example displays the following output:
' Converted '09' to True
' Unable to convert '12.6'
' Converted '0' to False
' Converted '-13 ' to True
比較布爾值
因為布爾值是 true
或 false
,因此幾乎沒有理由明確呼叫 CompareTo 方法,這表示實例是否大於、小於或等於指定的值。 一般而言,若要比較兩個布爾值變數,您可以呼叫 Equals 方法或使用語言的相等運算符。
不過,當您想要比較布爾變數與常值布爾值 true
或 false
時,不需要進行明確的比較,因為評估布爾值的結果是布爾值。 例如,下列兩個表達式相等,但第二個表達式比較精簡。 不過,這兩種技術都提供可比較的效能。
if (booleanValue == true) {
if booleanValue = true then
If booleanValue = True Then
if (booleanValue) {
if booleanValue then
If booleanValue Then
使用布爾值做為二進位值
布爾值會佔用一個字節的記憶體,如下列範例所示。 C# 範例必須使用 參數進行 /unsafe
編譯。
using System;
public struct BoolStruct
{
public bool flag1;
public bool flag2;
public bool flag3;
public bool flag4;
public bool flag5;
}
public class Example9
{
public static void Main()
{
unsafe {
BoolStruct b = new BoolStruct();
bool* addr = (bool*) &b;
Console.WriteLine("Size of BoolStruct: {0}", sizeof(BoolStruct));
Console.WriteLine("Field offsets:");
Console.WriteLine(" flag1: {0}", (bool*) &b.flag1 - addr);
Console.WriteLine(" flag1: {0}", (bool*) &b.flag2 - addr);
Console.WriteLine(" flag1: {0}", (bool*) &b.flag3 - addr);
Console.WriteLine(" flag1: {0}", (bool*) &b.flag4 - addr);
Console.WriteLine(" flag1: {0}", (bool*) &b.flag5 - addr);
}
}
}
// The example displays the following output:
// Size of BoolStruct: 5
// Field offsets:
// flag1: 0
// flag1: 1
// flag1: 2
// flag1: 3
// flag1: 4
#nowarn "9" "51"
open FSharp.NativeInterop
[<Struct>]
type BoolStruct =
val flag1: bool
val flag2: bool
val flag3: bool
val flag4: bool
val flag5: bool
let inline nint addr = NativePtr.toNativeInt addr
let mutable b = BoolStruct()
let addr = &&b
printfn $"Size of BoolStruct: {sizeof<BoolStruct>}"
printfn "Field offsets:"
printfn $" flag1: {nint &&b.flag1 - nint addr}"
printfn $" flag2: {nint &&b.flag2 - nint addr}"
printfn $" flag3: {nint &&b.flag3 - nint addr}"
printfn $" flag4: {nint &&b.flag4 - nint addr}"
printfn $" flag5: {nint &&b.flag5 - nint addr}"
// The example displays the following output:
// Size of BoolStruct: 5
// Field offsets:
// flag1: 0
// flag1: 1
// flag1: 2
// flag1: 3
// flag1: 4
位元組的低序位用來表示其值。 值 1 表示 true
,值為 0 表示 false
。
提示
您可以使用 System.Collections.Specialized.BitVector32 結構來處理布爾值集合。
您可以呼叫 BitConverter.GetBytes(Boolean) 方法,將布爾值轉換成其二進位表示法。 方法會傳回具有單一專案的位元組陣列。 若要從二進位表示法還原布爾值,您可以呼叫 BitConverter.ToBoolean(Byte[], Int32) 方法。
下列範例會呼叫 BitConverter.GetBytes 方法,將布爾值轉換成其二進位表示法,並顯示值的個別位,然後呼叫 BitConverter.ToBoolean 方法以從其二進位表示法還原值。
using System;
public class Example1
{
public static void Main()
{
bool[] flags = { true, false };
foreach (var flag in flags)
{
// Get binary representation of flag.
Byte value = BitConverter.GetBytes(flag)[0];
Console.WriteLine("Original value: {0}", flag);
Console.WriteLine("Binary value: {0} ({1})", value,
GetBinaryString(value));
// Restore the flag from its binary representation.
bool newFlag = BitConverter.ToBoolean(new Byte[] { value }, 0);
Console.WriteLine("Restored value: {0}\n", flag);
}
}
private static string GetBinaryString(Byte value)
{
string retVal = Convert.ToString(value, 2);
return new string('0', 8 - retVal.Length) + retVal;
}
}
// The example displays the following output:
// Original value: True
// Binary value: 1 (00000001)
// Restored value: True
//
// Original value: False
// Binary value: 0 (00000000)
// Restored value: False
open System
let getBinaryString (value: byte) =
let retValue = Convert.ToString(value, 2)
String('0', 8 - retValue.Length) + retValue
let flags = [ true; false ]
for flag in flags do
// Get binary representation of flag.
let value = BitConverter.GetBytes(flag)[0];
printfn $"Original value: {flag}"
printfn $"Binary value: {value} ({getBinaryString value})"
// Restore the flag from its binary representation.
let newFlag = BitConverter.ToBoolean([|value|], 0)
printfn $"Restored value: {newFlag}\n"
// The example displays the following output:
// Original value: True
// Binary value: 1 (00000001)
// Restored value: True
//
// Original value: False
// Binary value: 0 (00000000)
// Restored value: False
Module Example1
Public Sub Main()
Dim flags() As Boolean = {True, False}
For Each flag In flags
' Get binary representation of flag.
Dim value As Byte = BitConverter.GetBytes(flag)(0)
Console.WriteLine("Original value: {0}", flag)
Console.WriteLine("Binary value: {0} ({1})", value,
GetBinaryString(value))
' Restore the flag from its binary representation.
Dim newFlag As Boolean = BitConverter.ToBoolean({value}, 0)
Console.WriteLine("Restored value: {0}", flag)
Console.WriteLine()
Next
End Sub
Private Function GetBinaryString(value As Byte) As String
Dim retVal As String = Convert.ToString(value, 2)
Return New String("0"c, 8 - retVal.Length) + retVal
End Function
End Module
' The example displays the following output:
' Original value: True
' Binary value: 1 (00000001)
' Restored value: True
'
' Original value: False
' Binary value: 0 (00000000)
' Restored value: False
使用布爾值執行作業
本節說明布爾值如何在應用程式中使用。 第一節將討論其作為旗標的用法。 第二個說明其用於算術運算。
布爾值作為旗標
布爾值變數最常用來做為旗標,以表示存在或缺少某些條件。 例如,在方法中String.Compare(String, String, Boolean),最後一個參數 是一個旗標,ignoreCase
指出兩個字元串的比較是否不區分大小寫(為 true
) 或區分大小寫 (ignoreCase
ignoreCase
為 false
)。 然後,您可以在條件語句中評估旗標的值。
下列範例使用簡單的主控台應用程式來說明布爾變數作為旗標的使用方式。 應用程式接受命令行參數,讓輸出能夠重新導向至指定的檔案( /f
參數),並讓輸出同時傳送至指定的檔案和控制台( /b
參數)。 應用程式會定義名為 isRedirected
的旗標,以指出輸出是否要傳送至檔案,以及名為 isBoth
的旗標,指出輸出應該傳送至主控台。 F# 範例會使用 遞歸函式 來剖析自變數。
using System;
using System.IO;
using System.Threading;
public class Example5
{
public static void Main()
{
// Initialize flag variables.
bool isRedirected = false;
bool isBoth = false;
String fileName = "";
StreamWriter sw = null;
// Get any command line arguments.
String[] args = Environment.GetCommandLineArgs();
// Handle any arguments.
if (args.Length > 1) {
for (int ctr = 1; ctr < args.Length; ctr++) {
String arg = args[ctr];
if (arg.StartsWith("/") || arg.StartsWith("-")) {
switch (arg.Substring(1).ToLower())
{
case "f":
isRedirected = true;
if (args.Length < ctr + 2) {
ShowSyntax("The /f switch must be followed by a filename.");
return;
}
fileName = args[ctr + 1];
ctr++;
break;
case "b":
isBoth = true;
break;
default:
ShowSyntax(String.Format("The {0} switch is not supported",
args[ctr]));
return;
}
}
}
}
// If isBoth is True, isRedirected must be True.
if (isBoth && ! isRedirected) {
ShowSyntax("The /f switch must be used if /b is used.");
return;
}
// Handle output.
if (isRedirected) {
sw = new StreamWriter(fileName);
if (!isBoth)
Console.SetOut(sw);
}
String msg = String.Format("Application began at {0}", DateTime.Now);
Console.WriteLine(msg);
if (isBoth) sw.WriteLine(msg);
Thread.Sleep(5000);
msg = String.Format("Application ended normally at {0}", DateTime.Now);
Console.WriteLine(msg);
if (isBoth) sw.WriteLine(msg);
if (isRedirected) sw.Close();
}
private static void ShowSyntax(String errMsg)
{
Console.WriteLine(errMsg);
Console.WriteLine("\nSyntax: Example [[/f <filename> [/b]]\n");
}
}
open System
open System.IO
open System.Threading
let showSyntax errMsg =
printfn $"{errMsg}\n\nSyntax: Example [[/f <filename> [/b]]\n"
let mutable isRedirected = false
let mutable isBoth = false
let mutable fileName = ""
let rec parse = function
| [] -> ()
| "-b" :: rest
| "/b" :: rest ->
isBoth <- true
// Parse remaining arguments.
parse rest
| "-f" :: file :: rest
| "/f" :: file :: rest ->
isRedirected <- true
fileName <- file
// Parse remaining arguments.
parse rest
| "-f" :: []
| "/f" :: [] ->
isRedirected <- true
// No more arguments to parse.
| x -> showSyntax $"The {x} switch is not supported"
Environment.GetCommandLineArgs()[1..]
|> List.ofArray
|> parse
// If isBoth is True, isRedirected must be True.
if isBoth && not isRedirected then
showSyntax "The /f switch must be used if /b is used."
// If isRedirected is True, a fileName must be specified.
elif fileName = "" && isRedirected then
showSyntax "The /f switch must be followed by a filename."
else
use mutable sw = null
// Handle output.
let writeLine =
if isRedirected then
sw <- new StreamWriter(fileName)
if isBoth then
fun text ->
printfn "%s" text
sw.WriteLine text
else sw.WriteLine
else printfn "%s"
writeLine $"Application began at {DateTime.Now}"
Thread.Sleep 5000
writeLine $"Application ended normally at {DateTime.Now}"
Imports System.IO
Imports System.Threading
Module Example5
Public Sub Main()
' Initialize flag variables.
Dim isRedirected, isBoth As Boolean
Dim fileName As String = ""
Dim sw As StreamWriter = Nothing
' Get any command line arguments.
Dim args() As String = Environment.GetCommandLineArgs()
' Handle any arguments.
If args.Length > 1 Then
For ctr = 1 To args.Length - 1
Dim arg As String = args(ctr)
If arg.StartsWith("/") OrElse arg.StartsWith("-") Then
Select Case arg.Substring(1).ToLower()
Case "f"
isRedirected = True
If args.Length < ctr + 2 Then
ShowSyntax("The /f switch must be followed by a filename.")
Exit Sub
End If
fileName = args(ctr + 1)
ctr += 1
Case "b"
isBoth = True
Case Else
ShowSyntax(String.Format("The {0} switch is not supported",
args(ctr)))
Exit Sub
End Select
End If
Next
End If
' If isBoth is True, isRedirected must be True.
If isBoth And Not isRedirected Then
ShowSyntax("The /f switch must be used if /b is used.")
Exit Sub
End If
' Handle output.
If isRedirected Then
sw = New StreamWriter(fileName)
If Not isBoth Then
Console.SetOut(sw)
End If
End If
Dim msg As String = String.Format("Application began at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
Thread.Sleep(5000)
msg = String.Format("Application ended normally at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
If isRedirected Then sw.Close()
End Sub
Private Sub ShowSyntax(errMsg As String)
Console.WriteLine(errMsg)
Console.WriteLine()
Console.WriteLine("Syntax: Example [[/f <filename> [/b]]")
Console.WriteLine()
End Sub
End Module
布爾值和算術運算
布爾值有時用來指出觸發數學計算的條件是否存在。 例如, hasShippingCharge
變數可能會做為旗標,以指出是否要將出貨費用新增至發票金額。
由於具有 false
值的作業對運算的結果沒有任何影響,因此不需要將布爾值轉換成整數值,才能在數學運算中使用。 相反地,您可以使用條件式邏輯。
下列範例會計算由小計、出貨費用和選擇性服務費用所組成的金額。 變數 hasServiceCharge
會決定是否套用服務費用。 此範例會使用條件式邏輯來新增服務費用金額,而不是轉換成 hasServiceCharge
數值,並將它乘以服務費用金額。
using System;
public class Example6
{
public static void Main()
{
bool[] hasServiceCharges = { true, false };
Decimal subtotal = 120.62m;
Decimal shippingCharge = 2.50m;
Decimal serviceCharge = 5.00m;
foreach (var hasServiceCharge in hasServiceCharges) {
Decimal total = subtotal + shippingCharge +
(hasServiceCharge ? serviceCharge : 0);
Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.",
total, hasServiceCharge);
}
}
}
// The example displays output like the following:
// hasServiceCharge = True: The total is $128.12.
// hasServiceCharge = False: The total is $123.12.
let hasServiceCharges = [ true; false ]
let subtotal = 120.62M
let shippingCharge = 2.50M
let serviceCharge = 5.00M
for hasServiceCharge in hasServiceCharges do
let total =
subtotal + shippingCharge + if hasServiceCharge then serviceCharge else 0M
printfn $"hasServiceCharge = {hasServiceCharge}: The total is {total:C2}."
// The example displays output like the following:
// hasServiceCharge = True: The total is $128.12.
// hasServiceCharge = False: The total is $123.12.
Module Example6
Public Sub Main()
Dim hasServiceCharges() As Boolean = {True, False}
Dim subtotal As Decimal = 120.62D
Dim shippingCharge As Decimal = 2.5D
Dim serviceCharge As Decimal = 5D
For Each hasServiceCharge In hasServiceCharges
Dim total As Decimal = subtotal + shippingCharge +
If(hasServiceCharge, serviceCharge, 0)
Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.",
total, hasServiceCharge)
Next
End Sub
End Module
' The example displays output like the following:
' hasServiceCharge = True: The total is $128.12.
' hasServiceCharge = False: The total is $123.12.
布爾值和 Interop
雖然將基底數據類型封送處理至 COM 通常很簡單,但 Boolean 數據類型是例外狀況。 您可以將 屬性套用 MarshalAsAttribute 至將類型封送處理 Boolean 至下列任何表示法:
列舉類型 | Unmanaged 格式 |
---|---|
UnmanagedType.Bool | 4 位元組整數值,其中任何非零值都代表 true ,而0代表 false 。 這是結構中欄位的預設格式,也是Boolean平台調用呼叫中參數的預設格式Boolean。 |
UnmanagedType.U1 | 1 位元組整數值,其中1表示 true ,而0表示 false 。 |
UnmanagedType.VariantBool | 2 位元組整數值,其中 -1 代表 true ,而 0 表示 false 。 這是 COM Interop 呼叫中參數的預設格式 Boolean 。 |