Boolean Boolean Boolean Boolean Struct

Definition

表示一个布尔(truefalse)值。 Represents a Boolean (true or false) value.

public value class Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
type bool = struct
    interface IConvertible
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean)
Inheritance
Attributes
ComVisibleAttribute SerializableAttribute
Implements

Remarks

一个Boolean实例可以有两个值之一: true,或falseA 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:

格式设置的布尔值 Formatting Boolean values
转换到和从布尔值 Converting to and from Boolean values
分析布尔值 Parsing Boolean values
将布尔值进行比较 Comparing Boolean values
使用布尔值作为二进制值 Working with Booleans as binary values
使用布尔值执行运算 Performing operations with Boolean values
布尔值和互操作Booleans and Interop

格式设置的布尔值Formatting 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值定义的只读TrueStringFalseString字段。The 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.

下面的示例演示使用格式设置ToString方法。The 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 中。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值为"是"和"No"而不是"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. 下面的示例实现ICustomFormatterIFormatProvider接口为英语 (美国)、 法语 (法国) 和俄语 (俄罗斯) 区域性提供区分区域性的布尔值字符串。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.

转换到和从布尔值Converting to and from Boolean values

Boolean结构实现IConvertible接口。The Boolean structure implements the IConvertible interface. 因此,可以使用Convert类来执行之间的转换Boolean值以及任何其他基元类型,.NET Framework 中,或者您可以调用Boolean结构的显式实现。As a result, you can use the Convert class to perform conversions between a Boolean value and any other primitive type in the .NET Framework, 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.ToBoolean类。The 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

当从浮点值转换为布尔值,转换方法执行带零的精确比较。When converting from floating-point values to Boolean values, the conversion methods perform an exact comparison with zero. 如果浮点值已丢失精度,结果可能会意外。If the floating-point value has lost precision, the result can be unexpected. 在以下示例中,在其中阐释了这Double其值应为零的变量转换为布尔值。This is illustrated in the following example, in which a Double variable whose value should be zero is converted to a Boolean value. 如示例所示,结果是true因为重复的 0.2 会导致精度损失。As the example shows, the result is true because repeated additions of 0.2 have resulted in a loss of precision.

一个布尔值转换为数值的转换方法时Convert类 converttrue为 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.

分析布尔值Parsing Boolean values

Boolean结构包含两个静态分析方法ParseTryParse,字符串转换为布尔值。The Boolean structure includes two static parsing methods, Parse and TryParse, that convert a string to a Boolean value. 一个布尔值的字符串表示形式定义的值等效的不区分大小写TrueStringFalseString字段,它们将"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

将布尔值进行比较Comparing 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.

但是,当你想要比较的文字的布尔值的布尔变量truefalse,它不需要进行显式比较,因为的计算的布尔值结果是该布尔值。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) {
If booleanValue Then

and

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.

是等效的但第二个是更紧凑。are equivalent, but the second is more compact. 但是,这两种技术提供水平相当的性能。However, both techniques offer comparable performance.

使用布尔值作为二进制值Working with Booleans as binary values

一个布尔值占用一个字节的内存,如以下 C# 示例所示。A Boolean value occupies one byte of memory, as the following C# example shows. 必须使用编译该示例/unsafe切换。The 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

使用布尔值执行运算Performing 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,是一个标志,指示两个字符串的比较不区分大小写 (ignoreCasetrue) 或区分大小写 (ignoreCasefalse)。For 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切换),并启用要发送到指定的文件并向控制台输出 (/b切换)。The 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.

布尔值和互操作Booleans 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 2 字节的整数值,其中-1 表示true中,0 表示falseA 2-byte integer value, where -1 represents true and 0 represents false. 这是默认格式的BooleanCOM 互操作调用中的参数。This is the default format of a Boolean parameter in COM interop calls.

Fields

FalseString FalseString FalseString FalseString

将布尔值 false 表示为一个字符串。 Represents the Boolean value false as a string. 此字段为只读。 This field is read-only.

TrueString TrueString TrueString TrueString

将布尔值 true 表示为一个字符串。 Represents the Boolean value true as a string. 此字段为只读。 This field is read-only.

Methods

CompareTo(Boolean) CompareTo(Boolean) CompareTo(Boolean) CompareTo(Boolean)

将此实例与指定的 Boolean 对象进行比较,并返回一个指示二者关系的整数。 Compares this instance to a specified Boolean object and returns an integer that indicates their relationship to one another.

CompareTo(Object) CompareTo(Object) CompareTo(Object) CompareTo(Object)

将此实例与指定对象进行比较,并返回一个指示二者关系的整数。 Compares this instance to a specified object and returns an integer that indicates their relationship to one another.

Equals(Boolean) Equals(Boolean) Equals(Boolean) Equals(Boolean)

返回一个值,该值指示此实例是否与指定的 Boolean 相等。 Returns a value indicating whether this instance is equal to a specified Boolean object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。 Returns a value indicating whether this instance is equal to a specified object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。 Returns the hash code for this instance.

GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

返回 Boolean 值类型的类型代码。 Returns the type code for the Boolean value type.

Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>)
Parse(String) Parse(String) Parse(String) Parse(String)

将逻辑值的指定字符串表示形式转换为其等效的 Boolean Converts the specified string representation of a logical value to its Boolean equivalent.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

将此实例的值转换为其等效字符串表示形式(“True”或“False”)。 Converts the value of this instance to its equivalent string representation (either "True" or "False").

ToString() ToString() ToString() ToString()

将此实例的值转换为其等效字符串表示形式(“True”或“False”)。 Converts the value of this instance to its equivalent string representation (either "True" or "False").

TryFormat(Span<Char>, Int32) TryFormat(Span<Char>, Int32) TryFormat(Span<Char>, Int32) TryFormat(Span<Char>, Int32)
TryParse(ReadOnlySpan<Char>, Boolean) TryParse(ReadOnlySpan<Char>, Boolean) TryParse(ReadOnlySpan<Char>, Boolean) TryParse(ReadOnlySpan<Char>, Boolean)
TryParse(String, Boolean) TryParse(String, Boolean) TryParse(String, Boolean) TryParse(String, Boolean)

尝试将逻辑值的指定字符串表示形式转换为其等效的 Boolean 值。 Tries to convert the specified string representation of a logical value to its Boolean equivalent. 一个指示转换是否成功的返回值。 A return value indicates whether the conversion succeeded or failed.

Explicit Interface Implementations

IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

有关此成员的说明,请参阅 ToBoolean(IFormatProvider) For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参阅 ToByte(IFormatProvider) For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

不支持此转换。 This conversion is not supported. 尝试使用此方法将引发 InvalidCastException Attempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

不支持此转换。 This conversion is not supported. 尝试使用此方法将引发 InvalidCastException Attempting to use this method throws an InvalidCastException.

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

有关此成员的说明,请参见 ToDecimal(IFormatProvider) For a description of this member, see ToDecimal(IFormatProvider)..

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

有关此成员的说明,请参见 ToDouble(IFormatProvider) For a description of this member, see ToDouble(IFormatProvider)..

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参阅 ToInt16(IFormatProvider) For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参阅 ToInt32(IFormatProvider) For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参阅 ToInt64(IFormatProvider) For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参阅 ToSByte(IFormatProvider) For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

有关此成员的说明,请参见 ToSingle(IFormatProvider) For a description of this member, see ToSingle(IFormatProvider)..

IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider) IConvertible.ToString(IFormatProvider)
IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参阅 ToType(Type, IFormatProvider) For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参阅 ToUInt16(IFormatProvider) For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参阅 ToUInt32(IFormatProvider) For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider)

有关此成员的说明,请参阅 ToUInt64(IFormatProvider) For a description of this member, see ToUInt64(IFormatProvider).

Applies to

Thread Safety

此类型所有成员都是线程安全。 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.