Boolean 结构

定义

表示一个布尔(truefalse)值。

public value class bool : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public value class bool : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>, IParsable<bool>, ISpanParsable<bool>
public value class bool : IComparable, IConvertible
public value class bool : IComparable, IComparable<bool>, IEquatable<bool>
public struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public readonly struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>
public readonly struct Boolean : IComparable, IComparable<bool>, IConvertible, IEquatable<bool>, IParsable<bool>, ISpanParsable<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
type bool = struct
    interface IConvertible
    interface IParsable<bool>
    interface ISpanParsable<bool>
[<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, IComparable(Of Boolean), IConvertible, IEquatable(Of Boolean), IParsable(Of Boolean), ISpanParsable(Of Boolean)
Public Structure Boolean
Implements IComparable, IConvertible
Public Structure Boolean
Implements IComparable, IComparable(Of Boolean), IEquatable(Of Boolean)
继承
Boolean
属性
实现

注解

实例 Boolean 可以有两个值之一: truefalse

结构 Boolean 提供支持以下任务的方法:

以下部分介绍了这些任务和其他使用情况详细信息:

设置布尔值的格式

值的字符串表示形式 Boolean 为“True”, true 对于值为 false “False”。 值的字符串表示形式 Boolean 由只读 TrueStringFalseString 字段定义。

使用 ToString 方法可将布尔值转换为字符串。 布尔结构包括两个 ToString 重载:无 ToString() 参数方法和 ToString(IFormatProvider) 方法,其中包括控制格式设置的参数。 但是,由于忽略此参数,这两个重载会生成相同的字符串。 方法 ToString(IFormatProvider) 不支持区分区域性的格式。

以下示例演示了 使用 方法进行 ToString 格式设置。 请注意,C# 和 VB 示例使用 复合格式设置 功能,而 F# 示例使用 字符串内插。 在这两种情况下, ToString 都隐式调用 方法。

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
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 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 只能有两个值,因此可以轻松添加自定义格式。 对于将其他字符串文本替换为“True”和“False”的简单自定义格式,可以使用语言支持的任何条件计算功能,例如 C# 中的 条件运算符 或 Visual Basic 中的 If 运算符 。 以下示例使用此方法将值的格式 Boolean 设置为“是”和“否”,而不是“True”和“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
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 实现。 以下示例实现 ICustomFormatterIFormatProvider 接口,为英语 (美国) 、法语 (法国) 和俄语 (俄罗斯) 区域性提供区分区域性的布尔字符串。

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

(可选)可以使用 资源文件 来定义特定于区域性的布尔字符串。

与布尔值进行转换和转换

结构 Boolean 实现 IConvertible 接口。 因此,可以使用 Convert 类在值与 .NET 中的任何其他基元类型之间 Boolean 执行转换,也可以调用结构的 Boolean 显式实现。 但是,不支持 在 和以下类型之间进行 Boolean 转换,因此相应的转换方法会引发 InvalidCastException 异常:

从整型或浮点数到布尔值的所有转换将非零值 true 转换为 ,将零值转换为 false。 以下示例通过调用 类的选定重载来说明这一 Convert.ToBoolean 点。

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
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 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。 但是,Visual Basic 转换函数转换为 true 255 ((用于转换为 Byte 值) )或 -1 ((对于所有其他数值转换) )。 以下示例使用 Convert 方法转换为true数值,对于 Visual Basic 示例,则使用 Visual Basic 语言自己的转换运算符进行转换。

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
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 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 到字符串值的转换,请参阅 设置布尔值的格式 部分。 有关从字符串到 Boolean 值的转换,请参阅 分析布尔值 部分。

分析布尔值

结构 Boolean 包括两个静态分析方法, ParseTryParse,用于将字符串转换为布尔值。 布尔值的字符串表示形式由 和 FalseString 字段值的不区分大小写的TrueString等效项定义,分别为“True”和“False”。 换句话说,成功分析的唯一字符串是“True”、“False”、“true”、“false”或某种混合大小写等效项。 无法成功分析数字字符串,例如“0”或“1”。 执行字符串比较时,不考虑前导或尾随空格字符。

以下示例使用 ParseTryParse 方法来分析多个字符串。 请注意,只能成功分析“True”和“False”不区分大小写的等效项。

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'
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 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 函数将数字的字符串表示形式转换为布尔值。 “0”转换为 false,任何非零值的字符串表示形式将 true转换为 。 如果不在 Visual Basic 中编程,则必须先将数字字符串转换为数字,然后再将其转换为布尔值。 以下示例通过将整数数组转换为布尔值来说明这一点。

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

比较布尔值

由于布尔值是 truefalse,因此没有理由显式调用 CompareTo 方法,这指示实例是大于、小于还是等于指定值。 通常,若要比较两个布尔变量,请调用 Equals 方法或使用语言的相等运算符。

但是,如果要将布尔变量与文本布尔值 truefalse进行比较,则无需进行显式比较,因为计算布尔值的结果是布尔值。 例如,表达式

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

if (booleanValue) {
if booleanValue then
If booleanValue Then

是等效的,但第二个更紧凑。 但是,这两种技术提供可比的性能。

使用布尔值作为二进制值

布尔值占用一字节内存,如以下 C# 或 F# 示例所示。 必须使用 开关编译 /unsafe C# 示例。

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
#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 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
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 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

使用布尔值执行操作

本部分说明如何在应用中使用布尔值。 第一部分讨论将其用作标志。 第二个说明其用于算术运算。

布尔值作为标志

布尔变量最常用作标志,以指示是否存在某些条件。 例如,在 方法中 String.Compare(String, String, Boolean) ,最后一个参数 是一个标志, ignoreCase指示两个字符串的比较是) 区分大小写 (ignoreCasetrue 还是) 区分大小写 (ignoreCasefalse 。 然后,可以在条件语句中计算标志的值。

以下示例使用一个简单的控制台应用来说明布尔变量作为标志的用法。 应用接受命令行参数,这些参数允许将输出重定向到开关) (/f 指定文件,并且允许将输出同时发送到指定文件和控制台 (/b 开关) 。 应用定义一个名为 的 isRedirected 标志以指示是否将输出发送到文件,以及一个名为 isBoth 的标志,指示输出应发送到控制台。 请注意,F# 示例使用 递归函数 来分析参数。

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");
   }
}
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 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

布尔值和算术运算

布尔值有时用于指示是否存在触发数学计算的条件。 例如,变量 hasShippingCharge 可能用作标志,以指示是否向发票金额添加发货费用。

由于具有 false 值的运算对运算的结果没有影响,因此不必将布尔值转换为整型值以用于数学运算。 相反,可以使用条件逻辑。

以下示例计算由小计、运费和可选服务费组成的金额。 变量 hasServiceCharge 确定是否应用了服务费。 此示例使用条件逻辑添加服务费金额(如果适用),而不是转换为 hasServiceCharge 数值并将其乘以服务费金额。

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.
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 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.

布尔值和互操作

虽然将基本数据类型封送到 COM 通常很简单,但 Boolean 数据类型是一个例外。 可以应用 MarshalAsAttribute 特性将类型封送 Boolean 给以下任何表示形式:

枚举类型 非托管格式
UnmanagedType.Bool 一个 4 字节整数值,其中任何非零值表示 true ,0 表示 false。 这是结构中字段的默认格式,也是Boolean平台调用中参数的默认格式Boolean
UnmanagedType.U1 一个 1 字节整数值,其中 1 表示 true ,0 表示 false
UnmanagedType.VariantBool 一个 2 字节整数值,其中 -1 表示 true ,0 表示 false。 这是 COM 互操作调用中参数的默认格式 Boolean

字段

FalseString

将布尔值 false 表示为一个字符串。 此字段为只读。

TrueString

将布尔值 true 表示为一个字符串。 此字段为只读。

方法

CompareTo(Boolean)

将此实例与指定的 Boolean 对象进行比较,并返回一个指示二者关系的整数。

CompareTo(Object)

将此实例与指定对象进行比较,并返回一个指示二者关系的整数。

Equals(Boolean)

返回一个值,该值指示此实例是否与指定的 Boolean 相等。

Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。

GetHashCode()

返回此实例的哈希代码。

GetTypeCode()

返回 Boolean 值类型的类型代码。

Parse(ReadOnlySpan<Char>)

将逻辑值的指定范围表示形式转换为它的等效 Boolean

Parse(String)

将逻辑值的指定字符串表示形式转换为其等效的 Boolean

ToString()

将此实例的值转换为其等效字符串表示形式(“True”或“False”)。

ToString(IFormatProvider)

将此实例的值转换为其等效字符串表示形式(“True”或“False”)。

TryFormat(Span<Char>, Int32)

尝试将当前布尔实例的值的格式设置为提供的字符范围。

TryParse(ReadOnlySpan<Char>, Boolean)

尝试将逻辑值的指定范围表示形式转换为它的等效 Boolean

TryParse(String, Boolean)

尝试将逻辑值的指定字符串表示形式转换为其等效的 Boolean 值。

显式接口实现

IComparable.CompareTo(Object)

将当前实例与同一类型的另一个对象进行比较,并返回一个整数,该整数指示当前实例在排序顺序中的位置是位于另一个对象之前、之后还是与其位置相同。

IConvertible.GetTypeCode()

返回此实例的 TypeCode

IConvertible.ToBoolean(IFormatProvider)

有关此成员的说明,请参见 ToBoolean(IFormatProvider)

IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参见 ToByte(IFormatProvider)

IConvertible.ToChar(IFormatProvider)

不支持此转换。 尝试使用此方法将引发 InvalidCastException

IConvertible.ToDateTime(IFormatProvider)

不支持此转换。 尝试使用此方法将引发 InvalidCastException

IConvertible.ToDecimal(IFormatProvider)

有关此成员的说明,请参见 ToDecimal(IFormatProvider)

IConvertible.ToDouble(IFormatProvider)

有关此成员的说明,请参见 ToDouble(IFormatProvider)

IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参见 ToInt16(IFormatProvider)

IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参见 ToInt32(IFormatProvider)

IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参见 ToInt64(IFormatProvider)

IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参见 ToSByte(IFormatProvider)

IConvertible.ToSingle(IFormatProvider)

有关此成员的说明,请参见 ToSingle(IFormatProvider)

IConvertible.ToString(IFormatProvider)

使用指定的区域性特定格式设置信息将此实例的值转换为等效字符串。

IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参见 ToType(Type, IFormatProvider)

IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参见 ToUInt16(IFormatProvider)

IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参见 ToUInt32(IFormatProvider)

IConvertible.ToUInt64(IFormatProvider)

有关此成员的说明,请参见 ToUInt64(IFormatProvider)

IParsable<Boolean>.Parse(String, IFormatProvider)

将字符串分析为值。

IParsable<Boolean>.TryParse(String, IFormatProvider, Boolean)

表示一个布尔(truefalse)值。

ISpanParsable<Boolean>.Parse(ReadOnlySpan<Char>, IFormatProvider)

将字符范围解析为值。

ISpanParsable<Boolean>.TryParse(ReadOnlySpan<Char>, IFormatProvider, Boolean)

表示一个布尔(truefalse)值。

适用于

线程安全性

此类型的所有成员都是线程安全的。 看起来修改实例状态的成员实际上返回使用新值初始化的新实例。 与任何其他类型一样,读取和写入包含此类型的实例的共享变量必须受到锁的保护,以确保线程安全。