Boolean 結構

定義

代表布林值 (truefalse)。Represents a Boolean (true or false) value.

public value class Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public value class Boolean : IComparable, IConvertible
public value class Boolean : IComparable, IComparable<bool>, IEquatable<bool>
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
[System.Serializable]
public struct Boolean : IComparable, IConvertible
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public struct Boolean : IComparable, IComparable<bool>, IEquatable<bool>
type bool = struct
    interface IConvertible
[<System.Serializable>]
type bool = struct
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type bool = struct
    interface IConvertible
type bool = struct
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean)
Public Structure Boolean
Implements IComparable, IConvertible
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IEquatable(Of Boolean)
繼承
Boolean
屬性
實作

備註

Boolean實例可以有兩個值之一: truefalseA Boolean instance can have either of two values: true or false.

Boolean結構會提供支援下列工作的方法:The Boolean structure provides methods that support the following tasks:

下列各節將說明這些工作和其他使用方式的詳細資料:The following sections explain these tasks and other usage details:

格式化布林值Format Boolean values

的字串表示為 Boolean "True" 代表 true 值,"False" 表示 false 值。The string representation of a Boolean is either "True" for a true value or "False" for a false value. 值的字串表示 Boolean 是由唯讀 TrueString 和欄位所定義 FalseStringThe string representation of a Boolean value is defined by the read-only TrueString and FalseString fields.

您可以使用 ToString 方法,將布林值轉換成字串。You use the ToString method to convert Boolean values to strings. 布林結構包含兩個多載 ToString :無參數 ToString() 方法和 ToString(IFormatProvider) 方法,包括控制格式的參數。The Boolean structure includes two ToString overloads: the parameterless ToString() method and the ToString(IFormatProvider) method, which includes a parameter that controls formatting. 不過,因為這個參數會被忽略,所以這兩個多載會產生相同的字串。However, because this parameter is ignored, the two overloads produce identical strings. ToString(IFormatProvider)方法不支援區分文化特性的格式。The ToString(IFormatProvider) method does not support culture-sensitive formatting.

下列範例說明如何使用方法進行格式化 ToStringThe following example illustrates formatting with the ToString method. 請注意,此範例會使用 複合格式 功能,因此 ToString 會隱含地呼叫方法。Note that the example uses the composite formatting feature, so the ToString method is called implicitly.

using System;

public class Example
{
   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
Module Example
   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 結構只能有兩個值,所以很容易就能加入自訂格式。Because the Boolean structure can have only two values, it is easy to add custom formatting. 針對簡單的自訂格式,其他字串常值取代為 "True" 和 "False",您可以使用您的語言所支援的任何條件式評估功能,例如 c # 中的 條件運算子 或 Visual Basic 中的 If 運算子For simple custom formatting in which other string literals are substituted for "True" and "False", you can use any conditional evaluation feature supported by your language, such as the conditional operator in C# or the If operator in Visual Basic. 下列範例會使用這項技術,將值格式化為「是」和「否」, Boolean 而不是「True」和「False」。The following example uses this technique to format Boolean values as "Yes" and "No" rather than "True" and "False".

using System;

public class Example
{
   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

如需更複雜的自訂格式作業,包括區分文化特性的格式設定,您可以呼叫 String.Format(IFormatProvider, String, Object[]) 方法並提供 ICustomFormatter 執行。For more complex custom formatting operations, including culture-sensitive formatting, you can call the String.Format(IFormatProvider, String, Object[]) method and provide an ICustomFormatter implementation. 下列範例會 ICustomFormatter IFormatProvider 執行和介面,以針對英文 (美國) 、法文 (法國) 和俄文 (俄羅斯) 文化特性,提供區分文化特性的布林字串。The following example implements the ICustomFormatter and IFormatProvider interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures.

using System;
using System.Globalization;

public class Example
{
   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': верно
Imports System.Globalization

Module Example
   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': верно

(選擇性)您可以使用 資源檔 來定義特定文化特性的布林字串。Optionally, you can use resource files to define culture-specific Boolean strings.

從布林值轉換為和來源Convert to and from Boolean values

結構會實 Boolean 作為 IConvertible 介面。The Boolean structure implements the IConvertible interface. 如此一來,您就可以使用 Convert 類別, Boolean 在 .net 中的值和任何其他基本類型之間執行轉換,也可以呼叫 Boolean 結構的明確實作為。As a result, you can use the Convert class to perform conversions between a Boolean value and any other primitive type in .NET, or you can call the Boolean structure's explicit implementations. 但是, Boolean 不支援與下列類型之間的轉換,所以對應的轉換方法會擲回 InvalidCastException 例外狀況:However, conversions between a Boolean and the following types are not supported, so the corresponding conversion methods throw an InvalidCastException exception:

從整數或浮點數到布林值的所有轉換,會將非零值轉換成 true 零值 falseAll conversions from integral or floating-point numbers to Boolean values convert non-zero values to true and zero values to false. 下列範例會藉由呼叫類別的選取多載來說明這一點 Convert.ToBooleanThe following example illustrates this by calling selected overloads of the Convert.ToBoolean class.

using System;

public class Example
{
   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
Module Example
   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 = .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。When converting from Boolean to numeric values, the conversion methods of the Convert class convert true to 1 and false to 0. 不過,Visual Basic 轉換函式會轉換成 true 255 (來轉換成 Byte 值) 或-1 (用於所有其他的數值轉換) 。However, Visual Basic conversion functions convert true to either 255 (for conversions to Byte values) or -1 (for all other numeric conversions). 下列範例會 true 使用方法來轉換成數值 Convert ,而在 Visual Basic 範例的情況下,使用 Visual Basic 語言本身的轉換運算子。The following example converts true to numeric values by using a Convert method, and, in the case of the Visual Basic example, by using the Visual Basic language's own conversion operator.

using System;

public class Example
{
   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
Module Example
   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若要從轉換成字串值,請參閱格式化布林值一節。For conversions from Boolean to string values, see the Formatting Boolean Values section. 如需將字串轉換成 Boolean 值,請參閱 剖析布林值 一節。For conversions from strings to Boolean values, see the Parsing Boolean Values section.

剖析布林值Parse Boolean values

Boolean結構包含兩個靜態剖析方法, Parse 以及 TryParse 將字串轉換成布林值的。The Boolean structure includes two static parsing methods, Parse and TryParse, that convert a string to a Boolean value. 布林值的字串表示是由和欄位值不區分大小寫的對等專案所定義 TrueString FalseString ,分別為 "True" 和 "False"。The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the TrueString and FalseString fields, which are "True" and "False", respectively. 換句話說,唯一剖析成功的字串為 "True"、"False"、"true"、"false" 或某些混合案例的相等。In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. 您無法成功剖析數值字串,例如 "0" 或 "1"。You cannot successfully parse numeric strings such as "0" or "1". 執行字串比較時,不會考慮前置或尾端的空白字元。Leading or trailing white-space characters are not considered when performing the string comparison.

下列範例會使用 ParseTryParse 方法來剖析多個字串。The following example uses the Parse and TryParse methods to parse a number of strings. 請注意,只能成功剖析 "True" 和 "False" 的不區分大小寫對應項。Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed.

using System;

public class Example
{
   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'
Module Example
   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)
            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 數位的字串表示轉換成布林值。If you are programming in Visual Basic, you can use the CBool function to convert the string representation of a number to a Boolean value. "0" 會轉換為 false ,而且任何非零值的字串表示都會轉換成 true"0" is converted to false, and the string representation of any non-zero value is converted to true. 如果您不是在 Visual Basic 中進行程式設計,您必須先將數值字串轉換成數位,再將它轉換成布林值。If you are not programming in Visual Basic, you must convert your numeric string to a number before converting it to a Boolean. 下列範例說明如何將整數陣列轉換為布林值。The following example illustrates this by converting an array of integers to Boolean values.

using System;

public class Example
{
   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
Module Example
   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

比較布林值Compare Boolean values

因為布林值是 truefalse ,所以明確呼叫方法的原因很少 CompareTo ,這表示實例是否大於、小於或等於指定的值。Because Boolean values are either true or false, there is little reason to explicitly call the CompareTo method, which indicates whether an instance is greater than, less than, or equal to a specified value. 一般而言,若要比較兩個布林值變數,您可以呼叫 Equals 方法,或使用您的語言等號比較運算子。Typically, to compare two Boolean variables, you call the Equals method or use your language's equality operator.

但是,當您想要比較布林值變數與常值布林值 true 或時 false ,不需要執行明確的比較,因為評估布林值的結果就是布林值。However, when you want to compare a Boolean variable with the literal Boolean value true or false, it is not necessary to do an explicit comparison, because the result of evaluating a Boolean value is that Boolean value. 例如,運算式For example, the expressions

if (booleanValue == true) {
If booleanValue = True Then

and

if (booleanValue) {
If booleanValue Then

相等,但第二個較精簡。are equivalent, but the second is more compact. 不過,這兩種技術都提供相當的效能。However, both techniques offer comparable performance.

以二進位值使用布林值Work with Booleans as binary values

布林值會佔用一個位元組的記憶體,如下列 c # 範例所示。A Boolean value occupies one byte of memory, as the following C# example shows. 此範例必須使用參數來編譯 /unsafeThe example must be compiled with the /unsafe switch.

using System;

public struct BoolStruct
{
   public bool flag1;
   public bool flag2;
   public bool flag3;
   public bool flag4;
   public bool flag5;
}

public class Example
{
   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

位元組的低序位位是用來表示它的值。The byte's low-order bit is used to represent its value. 值為1表示 true ,值為0表示 falseA value of 1 represents true; a value of 0 represents false.

提示

您可以使用此 System.Collections.Specialized.BitVector32 結構來處理一組布林值。You can use the System.Collections.Specialized.BitVector32 structure to work with sets of Boolean values.

您可以藉由呼叫方法,將布林值轉換成二進位標記法 BitConverter.GetBytes(Boolean)You can convert a Boolean value to its binary representation by calling the BitConverter.GetBytes(Boolean) method. 方法會傳回具有單一元素的位元組陣列。The method returns a byte array with a single element. 若要從二進位標記法還原布林值,您可以呼叫 BitConverter.ToBoolean(Byte[], Int32) 方法。To restore a Boolean value from its binary representation, you can call the BitConverter.ToBoolean(Byte[], Int32) method.

下列範例會呼叫方法,將 BitConverter.GetBytes 布林值轉換為其二進位標記法,並顯示值的個別位,然後呼叫 BitConverter.ToBoolean 方法以從其二進位表示還原值。The following example calls the BitConverter.GetBytes method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the BitConverter.ToBoolean method to restore the value from its binary representation.

using System;

public class Example
{
   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
Module Example
   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

使用布林值執行作業Perform operations with Boolean values

本節說明如何在應用程式中使用布林值。This section illustrates how Boolean values are used in apps. 第一個章節討論其作為旗標的用法。The first section discusses its use as a flag. 第二個示範用於算數運算。The second illustrates its use for arithmetic operations.

以旗標形式的布林值Boolean values as flags

布林值變數最常用作為旗標,以表示有某些條件存在或不存在。Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. 例如,在方法中, String.Compare(String, String, Boolean) 最後 ignoreCase 一個參數是一個旗標,這個旗標會指出兩個字串的比較是否區分大小寫 (ignoreCase 是否) , true 或) 區分大小寫 (ignoreCase falseFor example, in the String.Compare(String, String, Boolean) method, the final parameter, ignoreCase, is a flag that indicates whether the comparison of two strings is case-insensitive (ignoreCase is true) or case-sensitive (ignoreCase is false). 然後可以在條件陳述式中評估旗標的值。The value of the flag can then be evaluated in a conditional statement.

下列範例會使用簡單的主控台應用程式,說明如何使用布林值變數作為旗標。The following example uses a simple console app to illustrate the use of Boolean variables as flags. 應用程式會接受命令列參數,以便將輸出重新導向至參數) (指定的檔案 /f ,並允許將輸出傳送至指定的檔案,並 (交換器) 傳送至主控台 /bThe app accepts command-line parameters that enable output to be redirected to a specified file (the /f switch), and that enable output to be sent both to a specified file and to the console (the /b switch). 應用程式會定義一個名 isRedirected 為的旗標,指出是否要將輸出傳送至檔案,並定義名為的旗 isBoth 標,以指出應將輸出傳送至主控台。The app defines a flag named isRedirected to indicate whether output is to be sent to a file, and a flag named isBoth to indicate that output should be sent to the console.

using System;
using System.IO;
using System.Threading;

public class Example
{
   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");
   }
}
Imports System.IO
Imports System.Threading

Module Example
   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

布林值和算數運算Booleans and arithmetic operations

布林值有時會用來指出觸發數學計算的條件是否存在。A Boolean value is sometimes used to indicate the presence of a condition that triggers a mathematical calculation. 例如, hasShippingCharge 變數可以作為旗標,以指出是否要將出貨費用新增至發票金額。For example, a hasShippingCharge variable might serve as a flag to indicate whether to add shipping charges to an invoice amount.

由於具有值的作業 false 不會影響作業的結果,因此不需要將布林值轉換成整數值,以在數學運算中使用。Because an operation with a false value has no effect on the result of an operation, it is not necessary to convert the Boolean to an integral value to use in the mathematical operation. 相反地,您可以使用條件式邏輯。Instead, you can use conditional logic.

下列範例會計算包含小計、出貨費用和選擇性服務費用的金額。The following example computes an amount that consists of a subtotal, a shipping charge, and an optional service charge. hasServiceCharge變數會決定是否要套用服務費用。The hasServiceCharge variable determines whether the service charge is applied. hasServiceCharge此範例會使用條件式邏輯來新增服務費用(如果適用的話),而不是轉換成數值並將它乘以服務費用的數量。Instead of converting hasServiceCharge to a numeric value and multiplying it by the amount of the service charge, the example uses conditional logic to add the service charge amount if it is applicable.

using System;

public class Example
{
   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.
Module Example
   Public Sub Main()
      Dim hasServiceCharges() As Boolean = { True, False }
      Dim subtotal As Decimal = 120.62d
      Dim shippingCharge As Decimal = 2.50d
      Dim serviceCharge As Decimal = 5.00d
      
      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.

布林值和 interopBooleans and interop

雖然將基底資料類型封送處理為 COM 通常很簡單,但 Boolean 資料類型是例外狀況。While marshaling base data types to COM is generally straightforward, the Boolean data type is an exception. 您可以套用屬性,將 MarshalAsAttribute 類型封送處理 Boolean 為下列任何一種標記法:You can apply the MarshalAsAttribute attribute to marshal the Boolean type to any of the following representations:

列舉類型Enumeration type 非受控格式Unmanaged format
UnmanagedType.Bool 4位元組整數值,其中任何非零值代表, true 0 代表 falseA 4-byte integer value, where any nonzero value represents true and 0 represents false. 這是架構中的欄位預設格式 Boolean ,以及 Boolean 平台叫用呼叫中的參數格式。This is the default format of a Boolean field in a structure and of a Boolean parameter in platform invoke calls.
UnmanagedType.U1 1位元組的整數值,其中1代表 true 和0代表 falseA 1-byte integer value, where the 1 represents true and 0 represents false.
UnmanagedType.VariantBool 雙位元組整數值,其中-1 代表 true 和0代表 falseA 2-byte integer value, where -1 represents true and 0 represents false. 這是 Boolean COM interop 呼叫中參數的預設格式。This is the default format of a Boolean parameter in COM interop calls.

欄位

FalseString

將布林值 false 表示為字串。Represents the Boolean value false as a string. 此欄位為唯讀。This field is read-only.

TrueString

將布林值 true 表示為字串。Represents the Boolean value true as a string. 此欄位為唯讀。This field is read-only.

方法

CompareTo(Boolean)

比較這個執行個體與指定的 Boolean 物件,並傳回整數,這個整數表示兩者彼此的關聯性。Compares this instance to a specified Boolean object and returns an integer that indicates their relationship to one another.

CompareTo(Object)

將這個執行個體與指定的物件相比較,並傳回整數,這個整數表示兩者彼此的關聯性 (Relationship)。Compares this instance to a specified object and returns an integer that indicates their relationship to one another.

Equals(Boolean)

傳回表示這個執行個體是否等於指定 Boolean 物件的值。Returns a value indicating whether this instance is equal to a specified Boolean object.

Equals(Object)

傳回值,該值表示這個執行個體是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

GetTypeCode()

傳回 Boolean 實值類型的類型程式碼。Returns the type code for the Boolean value type.

Parse(ReadOnlySpan<Char>)

將代表邏輯值的指定範圍轉換為其對等 BooleanConverts the specified span representation of a logical value to its Boolean equivalent.

Parse(String)

將指定之邏輯值的字串表示,轉換為相等的 BooleanConverts the specified string representation of a logical value to its Boolean equivalent.

ToString()

將這個執行個體的值轉換為它的對等字串表示 ("True" 或 "False")。Converts the value of this instance to its equivalent string representation (either "True" or "False").

ToString(IFormatProvider)

將這個執行個體的值轉換為它的對等字串表示 ("True" 或 "False")。Converts the value of this instance to its equivalent string representation (either "True" or "False").

TryFormat(Span<Char>, Int32)

嘗試將目前布林執行個體的值格式化為所提供字元範圍。Tries to format the value of the current boolean instance into the provided span of characters.

TryParse(ReadOnlySpan<Char>, Boolean)

嘗試將代表邏輯值的指定範圍轉換為對等 BooleanTries to convert the specified span representation of a logical value to its Boolean equivalent.

TryParse(String, Boolean)

嘗試將指定之邏輯值的字串表示轉換成對等的 BooleanTries to convert the specified string representation of a logical value to its Boolean equivalent.

明確介面實作

IComparable.CompareTo(Object)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

IConvertible.GetTypeCode()

傳回這個執行個體的 TypeCodeReturns the TypeCode for this instance.

IConvertible.ToBoolean(IFormatProvider)

如需這個成員的說明,請參閱 ToBoolean(IFormatProvider)For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider)

如需這個成員的說明,請參閱 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

不支援此轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider)

不支援此轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDecimal(IFormatProvider)

如需這個成員的說明,請參閱 ToDecimal(IFormatProvider)For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider)

如需這個成員的說明,請參閱 ToDouble(IFormatProvider)For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

如需這個成員的說明,請參閱 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

如需這個成員的說明,請參閱 ToSingle(IFormatProvider)For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToString(IFormatProvider)

使用指定限定文化特性的格式資訊,將此執行個體的值轉換為相等字串。Converts the value of this instance to an equivalent string using the specified culture-specific formatting information.

IConvertible.ToType(Type, IFormatProvider)

如需這個成員的說明,請參閱 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt64(IFormatProvider)For a description of this member, see ToUInt64(IFormatProvider).

適用於

執行緒安全性

此類型的所有成員都是安全線程。All members of this type are thread safe. 看似修改實例狀態的成員,實際上會傳回以新值初始化的新實例。Members that appear to modify instance state actually return a new instance initialized with the new value. 如同任何其他類型,讀取和寫入包含此類型之實例的共用變數,都必須受到鎖定的保護,以保證執行緒安全。As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.